| 1. |
Using stacks, write an algorithm to determine whether an infix expression has balanced parenthesis or not. |
|
Answer» The algorithm to determine whether an infix expression has a balanced parenthesis or not. Matching = TRUE Clear the stack; Read a symbol from input string While not end of input string and matching do { if (symbol= ‘(‘ or symbol = ‘{’ or symbol = ‘[’ ) push (symbol, stack) else (if symbol = ‘)’ or symbol = ‘}’ or symbol = ‘]’ ) if stack is empty matching = FALSE write (“more right parenthesis than left parentheses”) else c=pop (stack) match c and the input symbol if not matched { matching = FALSE write (“error, mismatched parentheses”) } read the next input symbol } if stack is empty then write ( “ parentheses are balanced properly”) else write (“more left parentheses then right parentheses”) |
|