Computer Science, asked by triptichoubey7212, 1 year ago

Which data structure is used to check whether an arithmetic expression has balanced parentheses?

Answers

Answered by prakash6032
3

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.

/*Return 1 if expression has balanced parentheses */

bool areParenthesesBalanced(expression )

{

for each character in expression

{

if(character == ’(’ || character == ’{’ || character == ’[’)

push(stack, character);

if(character == ’)’ || character == ’}’ || character == ’]’)

{

if(isEmpty(stack))

return 0; /*We are seeing a right parenthesis

without a left pair*/

/* Pop the top element from stack, if it is not a pair

bracket of character then there is a mismatch.

This will happen for expressions like {(}) */

else if (! isMatchingPair(pop(stack), character) )

return 0;

}

}

if(isEmpty(stack))

return 1; /*balanced*/

else

return 0; /*not balanced*/

} /* End of function to check parentheses */

/* Returns 1 if character1 and character2 are matching left

and right parentheses */

bool isMatchingPair(character1, character2)

{

if(character1 == ‘(‘ && character2 == ‘)’)

return 1;

else If(character1 == ‘{‘ && character2 == ‘}’)

return 1;

else If(character1 == ‘[‘ && character2 == ‘]’)

return 1;

else

return 0;

}

Answered by kdhiman24251
0

Explanation:

ihkkhhbhddvhyuihguiioooo

Similar questions