Data Structures | Misc | Question 4
The best data structure to check whether an arithmetic expression has balanced parentheses is a (GATE CS 2004)
(A) queue
(B) stack
(C) tree
(D) list
Answer: (B)
Explanation: There are three types of parentheses [ ] { } (). Below is an arbit c code segment which has parentheses of all three types.
void func( int c, int a[])
{
return ((c +2) + arr[(c-2)]) ;
}
|
Stack is a straightforward choice for checking if left and right parentheses are balanced. Here is a algorithm to do the same.
bool areParenthesesBalanced(expression )
{
for each character in expression
{
if (character == ’(’ || character == ’{’ || character == ’[’)
push(stack, character);
if (character == ’)’ || character == ’}’ || character == ’]’)
{
if (isEmpty(stack))
return 0;
else if (! isMatchingPair(pop(stack), character) )
return 0;
}
}
if (isEmpty(stack))
return 1;
else
return 0;
}
bool isMatchingPair(character1, character2)
{
if (character1 == ‘(‘ && character2 == ‘)’)
return 1;
else If(character1 == ‘{‘ && character2 == ‘}’)
return 1;
else If(character1 == ‘[‘ && character2 == ‘]’)
return 1;
else
return 0;
}
|
Quiz of this Question
Last Updated :
28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...