SlideShare a Scribd company logo
Given an expression string exp, write a java class ExpressionCheccker whose main method gets
exp in the input line of terminal and examines whether the pairs and the orders of ”(“,”)”,”[“,”]”
are correct in exp. For example, the program should print true for exp =“[()][()()]()” and false for
exp = “[(])”. ( Use stack)
Ans:
Algorithm:
1) Declare a character stack S.
2) Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the
popped character is the matching starting bracket then fine else parenthesis are not balanced.
3) After complete traversal, if there is some starting bracket left in stack then “not balanced”
Program:
#include
#include
#define bool int
/* structure of a stack node */
struct sNode
{
char data;
struct sNode *next;
};
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data);
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref);
/* Returns 1 if character1 and character2 are matching left
and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
int i = 0;
/* Declare an empty character stack */
struct sNode *stack = NULL;
/* Traverse the given expression to check matching parenthesis */
while (exp[i])
{
/*If the exp[i] is a starting parenthesis then push it*/
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
/* If exp[i] is a ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
/*If we see an ending parenthesis without a pair then return false*/
if (stack == NULL)
return 0;
/* Pop the top element from stack, if it is not a pair
parenthesis of character then there is a mismatch.
This happens for expressions like {(}) */
else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}
/* If there is something left in expression then there is a starting
parenthesis without a closing parenthesis */
if (stack == NULL)
return 1; /*balanced*/
else
return 0; /*not balanced*/
}
/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf(" Balanced ");
else
printf(" Not Balanced ");
return 0;
}
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
/* allocate node */
struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*top_ref);
/* move the head to point to the new node */
(*top_ref) = new_node;
}
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
/*If stack is empty then error */
if (*top_ref == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
#include
#include
#define bool int
/* structure of a stack node */
struct sNode
{
char data;
struct sNode *next;
};
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data);
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref);
/* Returns 1 if character1 and character2 are matching left
and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
int i = 0;
/* Declare an empty character stack */
struct sNode *stack = NULL;
/* Traverse the given expression to check matching parenthesis */
while (exp[i])
{
/*If the exp[i] is a starting parenthesis then push it*/
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
/* If exp[i] is a ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
/*If we see an ending parenthesis without a pair then return false*/
if (stack == NULL)
return 0;
/* Pop the top element from stack, if it is not a pair
parenthesis of character then there is a mismatch.
This happens for expressions like {(}) */
else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}
/* If there is something left in expression then there is a starting
parenthesis without a closing parenthesis */
if (stack == NULL)
return 1; /*balanced*/
else
return 0; /*not balanced*/
}
/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf(" Balanced ");
else
printf(" Not Balanced ");
return 0;
}
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
/* allocate node */
struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*top_ref);
/* move the head to point to the new node */
(*top_ref) = new_node;
}
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
/*If stack is empty then error */
if (*top_ref == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
Solution
Given an expression string exp, write a java class ExpressionCheccker whose main method gets
exp in the input line of terminal and examines whether the pairs and the orders of ”(“,”)”,”[“,”]”
are correct in exp. For example, the program should print true for exp =“[()][()()]()” and false for
exp = “[(])”. ( Use stack)
Ans:
Algorithm:
1) Declare a character stack S.
2) Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the
popped character is the matching starting bracket then fine else parenthesis are not balanced.
3) After complete traversal, if there is some starting bracket left in stack then “not balanced”
Program:
#include
#include
#define bool int
/* structure of a stack node */
struct sNode
{
char data;
struct sNode *next;
};
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data);
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref);
/* Returns 1 if character1 and character2 are matching left
and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
int i = 0;
/* Declare an empty character stack */
struct sNode *stack = NULL;
/* Traverse the given expression to check matching parenthesis */
while (exp[i])
{
/*If the exp[i] is a starting parenthesis then push it*/
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
/* If exp[i] is a ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
/*If we see an ending parenthesis without a pair then return false*/
if (stack == NULL)
return 0;
/* Pop the top element from stack, if it is not a pair
parenthesis of character then there is a mismatch.
This happens for expressions like {(}) */
else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}
/* If there is something left in expression then there is a starting
parenthesis without a closing parenthesis */
if (stack == NULL)
return 1; /*balanced*/
else
return 0; /*not balanced*/
}
/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf(" Balanced ");
else
printf(" Not Balanced ");
return 0;
}
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
/* allocate node */
struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*top_ref);
/* move the head to point to the new node */
(*top_ref) = new_node;
}
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
/*If stack is empty then error */
if (*top_ref == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
#include
#include
#define bool int
/* structure of a stack node */
struct sNode
{
char data;
struct sNode *next;
};
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data);
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref);
/* Returns 1 if character1 and character2 are matching left
and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
int i = 0;
/* Declare an empty character stack */
struct sNode *stack = NULL;
/* Traverse the given expression to check matching parenthesis */
while (exp[i])
{
/*If the exp[i] is a starting parenthesis then push it*/
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
/* If exp[i] is a ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
/*If we see an ending parenthesis without a pair then return false*/
if (stack == NULL)
return 0;
/* Pop the top element from stack, if it is not a pair
parenthesis of character then there is a mismatch.
This happens for expressions like {(}) */
else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}
/* If there is something left in expression then there is a starting
parenthesis without a closing parenthesis */
if (stack == NULL)
return 1; /*balanced*/
else
return 0; /*not balanced*/
}
/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf(" Balanced ");
else
printf(" Not Balanced ");
return 0;
}
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
/* allocate node */
struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*top_ref);
/* move the head to point to the new node */
(*top_ref) = new_node;
}
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
/*If stack is empty then error */
if (*top_ref == NULL)
{
printf("Stack overflow  ");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}

More Related Content

PDF
java write a program to evaluate the postfix expressionthe program.pdf
PDF
Please review my code (java)Someone helped me with it but i cannot.pdf
PPTX
STACKS implimentarions AND stack applications .pptx
DOCX
@author Derek Harter @cwid 123 45 678 @class .docx
PDF
The concept of stack is extremely important in computer science and .pdf
DOCX
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
DOCX
#C programming Question 35Implement the functions required for the.docx
java write a program to evaluate the postfix expressionthe program.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
STACKS implimentarions AND stack applications .pptx
@author Derek Harter @cwid 123 45 678 @class .docx
The concept of stack is extremely important in computer science and .pdf
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
#C programming Question 35Implement the functions required for the.docx

Similar to Given an expression string exp, write a java class ExpressionCheccke.pdf (20)

PDF
solution in c++program Program to implement a queue using two .pdf
PPT
7 stacksqueues
PDF
Data structure lab manual
PPTX
Data Structures and Agorithm: DS 06 Stack.pptx
PDF
Write a program that converts an infix expression into an equivalent.pdf
PDF
DOCX
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
PPTX
Ch05_Stacks implementation in data structures.pptx
PPTX
Ch05_Stacks implementation in data structures.pptx
PPT
Stack queue
PPT
Stack queue
PPT
Stack queue
PPT
Stack queue
PPT
Stack queue
PPT
Stack queue
PPT
Stack queue
PPT
Data Structure Lecture 2
PDF
VTU DSA Lab Manual
PDF
Implement the ADT stack by using an array stack to contain its entri.pdf
solution in c++program Program to implement a queue using two .pdf
7 stacksqueues
Data structure lab manual
Data Structures and Agorithm: DS 06 Stack.pptx
Write a program that converts an infix expression into an equivalent.pdf
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
Ch05_Stacks implementation in data structures.pptx
Ch05_Stacks implementation in data structures.pptx
Stack queue
Stack queue
Stack queue
Stack queue
Stack queue
Stack queue
Stack queue
Data Structure Lecture 2
VTU DSA Lab Manual
Implement the ADT stack by using an array stack to contain its entri.pdf

More from info382133 (20)

PDF
1.) Main characteristics of Haloarchaea are as followsHalophiles .pdf
PDF
1. The three bacteria that may be implicated in the given case are S.pdf
PDF
1. Pros and Cons of IP CCTVNew threats are introduced to the secu.pdf
PDF
1. Activation of Vit. D involves Kidney and Liver and liver is part .pdf
PDF
Rf = (distance the spot traveled)L there are fou.pdf
PDF
No. Since sodium chloride is an ionic compound, i.pdf
PDF
Nacl is highly ionic in nature. where as CaO is s.pdf
PDF
it is reduced as it accepts e- and goes from 0 to.pdf
PDF
Iodine test is used to see if a compound has star.pdf
PDF
I have no clue! .pdf
PDF
C only III is major product .pdf
PDF
Borane-THF is flammable and highly reactive with .pdf
PDF
Ubiquity Internet is available everywhere namely at home, at work v.pdf
PDF
Water is the most used resource in our day to day life . When the wa.pdf
PDF
The initiation of the sporulation of the bacteria is a complex cellu.pdf
PDF
The emissivity of a given surface is the measure of its ability to e.pdf
PDF
Power set={SolutionPower set={.pdf
PDF
bro Solutionbro .pdf
PDF
ANSWER Accounting concepts and conventions In dr.pdf
PDF
As ions are charged species a strong interactions.pdf
1.) Main characteristics of Haloarchaea are as followsHalophiles .pdf
1. The three bacteria that may be implicated in the given case are S.pdf
1. Pros and Cons of IP CCTVNew threats are introduced to the secu.pdf
1. Activation of Vit. D involves Kidney and Liver and liver is part .pdf
Rf = (distance the spot traveled)L there are fou.pdf
No. Since sodium chloride is an ionic compound, i.pdf
Nacl is highly ionic in nature. where as CaO is s.pdf
it is reduced as it accepts e- and goes from 0 to.pdf
Iodine test is used to see if a compound has star.pdf
I have no clue! .pdf
C only III is major product .pdf
Borane-THF is flammable and highly reactive with .pdf
Ubiquity Internet is available everywhere namely at home, at work v.pdf
Water is the most used resource in our day to day life . When the wa.pdf
The initiation of the sporulation of the bacteria is a complex cellu.pdf
The emissivity of a given surface is the measure of its ability to e.pdf
Power set={SolutionPower set={.pdf
bro Solutionbro .pdf
ANSWER Accounting concepts and conventions In dr.pdf
As ions are charged species a strong interactions.pdf

Recently uploaded (20)

PDF
Computing-Curriculum for Schools in Ghana
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Lesson notes of climatology university.
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Cell Types and Its function , kingdom of life
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Cell Structure & Organelles in detailed.
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Computing-Curriculum for Schools in Ghana
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
2.FourierTransform-ShortQuestionswithAnswers.pdf
Pharma ospi slides which help in ospi learning
O7-L3 Supply Chain Operations - ICLT Program
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Lesson notes of climatology university.
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Cell Types and Its function , kingdom of life
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Cell Structure & Organelles in detailed.
Chinmaya Tiranga quiz Grand Finale.pdf
Microbial disease of the cardiovascular and lymphatic systems
STATICS OF THE RIGID BODIES Hibbelers.pdf
GDM (1) (1).pptx small presentation for students
Chapter 2 Heredity, Prenatal Development, and Birth.pdf

Given an expression string exp, write a java class ExpressionCheccke.pdf

  • 1. Given an expression string exp, write a java class ExpressionCheccker whose main method gets exp in the input line of terminal and examines whether the pairs and the orders of ”(“,”)”,”[“,”]” are correct in exp. For example, the program should print true for exp =“[()][()()]()” and false for exp = “[(])”. ( Use stack) Ans: Algorithm: 1) Declare a character stack S. 2) Now traverse the expression string exp. a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack. b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced. 3) After complete traversal, if there is some starting bracket left in stack then “not balanced” Program: #include #include #define bool int /* structure of a stack node */ struct sNode { char data; struct sNode *next; }; /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data); /* Function to pop an item from stack*/ int pop(struct sNode** top_ref); /* Returns 1 if character1 and character2 are matching left and right Parenthesis */ bool isMatchingPair(char character1, char character2) { if (character1 == '(' && character2 == ')') return 1; else if (character1 == '{' && character2 == '}') return 1; else if (character1 == '[' && character2 == ']')
  • 2. return 1; else return 0; } /*Return 1 if expression has balanced Parenthesis */ bool areParenthesisBalanced(char exp[]) { int i = 0; /* Declare an empty character stack */ struct sNode *stack = NULL; /* Traverse the given expression to check matching parenthesis */ while (exp[i]) { /*If the exp[i] is a starting parenthesis then push it*/ if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') push(&stack, exp[i]); /* If exp[i] is a ending parenthesis then pop from stack and check if the popped parenthesis is a matching pair*/ if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { /*If we see an ending parenthesis without a pair then return false*/ if (stack == NULL) return 0; /* Pop the top element from stack, if it is not a pair parenthesis of character then there is a mismatch. This happens for expressions like {(}) */ else if ( !isMatchingPair(pop(&stack), exp[i]) ) return 0; } i++; } /* If there is something left in expression then there is a starting parenthesis without a closing parenthesis */ if (stack == NULL)
  • 3. return 1; /*balanced*/ else return 0; /*not balanced*/ } /* UTILITY FUNCTIONS */ /*driver program to test above functions*/ int main() { char exp[100] = "{()}[]"; if (areParenthesisBalanced(exp)) printf(" Balanced "); else printf(" Not Balanced "); return 0; } /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data) { /* allocate node */ struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow "); getchar(); exit(0); } /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref); /* move the head to point to the new node */ (*top_ref) = new_node; } /* Function to pop an item from stack*/ int pop(struct sNode** top_ref)
  • 4. { char res; struct sNode *top; /*If stack is empty then error */ if (*top_ref == NULL) { printf("Stack overflow "); getchar(); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; } } #include #include #define bool int /* structure of a stack node */ struct sNode { char data; struct sNode *next; }; /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data); /* Function to pop an item from stack*/ int pop(struct sNode** top_ref); /* Returns 1 if character1 and character2 are matching left and right Parenthesis */ bool isMatchingPair(char character1, char character2) {
  • 5. if (character1 == '(' && character2 == ')') return 1; else if (character1 == '{' && character2 == '}') return 1; else if (character1 == '[' && character2 == ']') return 1; else return 0; } /*Return 1 if expression has balanced Parenthesis */ bool areParenthesisBalanced(char exp[]) { int i = 0; /* Declare an empty character stack */ struct sNode *stack = NULL; /* Traverse the given expression to check matching parenthesis */ while (exp[i]) { /*If the exp[i] is a starting parenthesis then push it*/ if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') push(&stack, exp[i]); /* If exp[i] is a ending parenthesis then pop from stack and check if the popped parenthesis is a matching pair*/ if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { /*If we see an ending parenthesis without a pair then return false*/ if (stack == NULL) return 0; /* Pop the top element from stack, if it is not a pair parenthesis of character then there is a mismatch. This happens for expressions like {(}) */ else if ( !isMatchingPair(pop(&stack), exp[i]) ) return 0; } i++;
  • 6. } /* If there is something left in expression then there is a starting parenthesis without a closing parenthesis */ if (stack == NULL) return 1; /*balanced*/ else return 0; /*not balanced*/ } /* UTILITY FUNCTIONS */ /*driver program to test above functions*/ int main() { char exp[100] = "{()}[]"; if (areParenthesisBalanced(exp)) printf(" Balanced "); else printf(" Not Balanced "); return 0; } /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data) { /* allocate node */ struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow "); getchar(); exit(0); } /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref);
  • 7. /* move the head to point to the new node */ (*top_ref) = new_node; } /* Function to pop an item from stack*/ int pop(struct sNode** top_ref) { char res; struct sNode *top; /*If stack is empty then error */ if (*top_ref == NULL) { printf("Stack overflow "); getchar(); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; } } Solution Given an expression string exp, write a java class ExpressionCheccker whose main method gets exp in the input line of terminal and examines whether the pairs and the orders of ”(“,”)”,”[“,”]” are correct in exp. For example, the program should print true for exp =“[()][()()]()” and false for exp = “[(])”. ( Use stack) Ans: Algorithm: 1) Declare a character stack S. 2) Now traverse the expression string exp. a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
  • 8. b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced. 3) After complete traversal, if there is some starting bracket left in stack then “not balanced” Program: #include #include #define bool int /* structure of a stack node */ struct sNode { char data; struct sNode *next; }; /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data); /* Function to pop an item from stack*/ int pop(struct sNode** top_ref); /* Returns 1 if character1 and character2 are matching left and right Parenthesis */ bool isMatchingPair(char character1, char character2) { if (character1 == '(' && character2 == ')') return 1; else if (character1 == '{' && character2 == '}') return 1; else if (character1 == '[' && character2 == ']') return 1; else return 0; } /*Return 1 if expression has balanced Parenthesis */ bool areParenthesisBalanced(char exp[]) { int i = 0; /* Declare an empty character stack */ struct sNode *stack = NULL;
  • 9. /* Traverse the given expression to check matching parenthesis */ while (exp[i]) { /*If the exp[i] is a starting parenthesis then push it*/ if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') push(&stack, exp[i]); /* If exp[i] is a ending parenthesis then pop from stack and check if the popped parenthesis is a matching pair*/ if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { /*If we see an ending parenthesis without a pair then return false*/ if (stack == NULL) return 0; /* Pop the top element from stack, if it is not a pair parenthesis of character then there is a mismatch. This happens for expressions like {(}) */ else if ( !isMatchingPair(pop(&stack), exp[i]) ) return 0; } i++; } /* If there is something left in expression then there is a starting parenthesis without a closing parenthesis */ if (stack == NULL) return 1; /*balanced*/ else return 0; /*not balanced*/ } /* UTILITY FUNCTIONS */ /*driver program to test above functions*/ int main() { char exp[100] = "{()}[]"; if (areParenthesisBalanced(exp))
  • 10. printf(" Balanced "); else printf(" Not Balanced "); return 0; } /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data) { /* allocate node */ struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow "); getchar(); exit(0); } /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref); /* move the head to point to the new node */ (*top_ref) = new_node; } /* Function to pop an item from stack*/ int pop(struct sNode** top_ref) { char res; struct sNode *top; /*If stack is empty then error */ if (*top_ref == NULL) { printf("Stack overflow "); getchar(); exit(0); }
  • 11. else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; } } #include #include #define bool int /* structure of a stack node */ struct sNode { char data; struct sNode *next; }; /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data); /* Function to pop an item from stack*/ int pop(struct sNode** top_ref); /* Returns 1 if character1 and character2 are matching left and right Parenthesis */ bool isMatchingPair(char character1, char character2) { if (character1 == '(' && character2 == ')') return 1; else if (character1 == '{' && character2 == '}') return 1; else if (character1 == '[' && character2 == ']') return 1; else return 0; } /*Return 1 if expression has balanced Parenthesis */
  • 12. bool areParenthesisBalanced(char exp[]) { int i = 0; /* Declare an empty character stack */ struct sNode *stack = NULL; /* Traverse the given expression to check matching parenthesis */ while (exp[i]) { /*If the exp[i] is a starting parenthesis then push it*/ if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') push(&stack, exp[i]); /* If exp[i] is a ending parenthesis then pop from stack and check if the popped parenthesis is a matching pair*/ if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { /*If we see an ending parenthesis without a pair then return false*/ if (stack == NULL) return 0; /* Pop the top element from stack, if it is not a pair parenthesis of character then there is a mismatch. This happens for expressions like {(}) */ else if ( !isMatchingPair(pop(&stack), exp[i]) ) return 0; } i++; } /* If there is something left in expression then there is a starting parenthesis without a closing parenthesis */ if (stack == NULL) return 1; /*balanced*/ else return 0; /*not balanced*/ } /* UTILITY FUNCTIONS */
  • 13. /*driver program to test above functions*/ int main() { char exp[100] = "{()}[]"; if (areParenthesisBalanced(exp)) printf(" Balanced "); else printf(" Not Balanced "); return 0; } /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data) { /* allocate node */ struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow "); getchar(); exit(0); } /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref); /* move the head to point to the new node */ (*top_ref) = new_node; } /* Function to pop an item from stack*/ int pop(struct sNode** top_ref) { char res; struct sNode *top; /*If stack is empty then error */ if (*top_ref == NULL)
  • 14. { printf("Stack overflow "); getchar(); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; } }