2. Stack Application
• Parsing in a compiler
• Undo in a word processor
• Back button in a web browser
• Postscript language for printers
• Implementing a function call in compiler
3. Arithmetic Expression Evaluation
• Value: push onto value stack
• Operator: push onto operator stack
• Left parenthesis: ignore
• Right parenthesis: pop operator and two values. Push the result.
( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ))
4. Progress Value stack Operator stack Rule
( ignore
1 Push value on value stack
+ + Push value on operator stack
( Ignore
( Ignore
2 Push value on value stack
+ + Push value on operator stack
3 Push value on value stack
) Pop top operator and last 2 value stack element.
* * Push value on operator stack
( Ignore
4 Push value on value stack
* * Push value on operator stack
5 Push value on value stack
) Pop top operator and last 2 value stack element.
) Pop top operator and last 2 value stack element.
) Pop top operator and last 2 value stack element.
6. Algorithm
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else
1. If the precedence of scanned operator is greater than the precedence of the
operator in stack or stack is empty , push it.
2. Else, pop the operator from the stack until the precedence of the second
operator is less-equal to the precedence of the operator residing on the top
of the stack. Push the scanned operator to the stack.
7. Algorithm- contd.
4. If the scanned operator is ‘(‘, push it to the stack.
5. If the scanned operator is ‘)’, pop and output from the stack until an
‘(‘ is encountered.
6. Repeat 2-6 until the infix expression is scanned.
7. Pop and output from stack until stack is empty.
8. Example Explained
A+B-C
Infix progress postfix Stack content Rule
A
+
B
-
c
A
A+
A+B
A+B-
A+B-
A+B-c
A
A
AB
AB
AB+
AB+C
AB+C-
+
+
-
-
• Write operand to output
• If stack empty, push opThis
• Write operand to output
• Stack not empty- pop item
opTop >= opThis - output opTop
Push opThis
• Write operand to output
stack not empty- pop item and output it