CEG's Linux User Group

  • Increase font size
  • Default font size
  • Decrease font size
Home Labs Balancing parenthesis

Balancing parenthesis

E-mail Print
User Rating: / 7
PoorBest 
Article Index
Balancing parenthesis
Source code
Documentation
Compatibility & Reference
All Pages

BALANCING PARENTHESIS

Introduction:

Balancing parenthesis is one of the most common application of stack. The expression is got an input from the user. Then each char is examined. If the character is a opening parenthesis, then it is pushed into the stack. If the character is a closing parenthesis, we pop the top element from the stack and check if it makes a valid couple of brackets with the examined element.

If this is not the case, the series is not balanced, otherwise we can discard both parenthesis and go on with the next character, until the series is over.

When there are no parenthesis left to examine, if the stack is empty then the expression is valid; if there are still elements on the stack we can conclude that the series is unbalanced.

For example, consider this example ({})

input expression array

Bracket

Stack

Bracket2

Since '(' and '{' are opening parenthesis, they are pushed into the stack. When '}' is encountered, the top-most element ( '{' ) of the stack is popped and is checked if it makes a valid couple of brackets.
So, '{' and '}' are discarded and ')' is considered.
Stack
Bracket3
Empty stack
Bracket4

Now '(' is popped and checked with ')'. They are discarded as they match. When the NULL character ('\0') is reached, the stack is empty so, the expression is balanced.


Last Updated on Saturday, 06 June 2009 19:13  
Please register or login to add your comments to this article.