Application of Stacks
Application of Stacks
Application of Stacks
Reversing a Line
Parenthesis Matching – to match left and right parenthesis
in an expression.
Converting Infix arithmetic expression to Postfix or Prefix
form.
Evaluation of a Postfix or Prefix arithmetic expression.
Execution of Nested and Recursive function calls.
(will be discussed in Grade 12)
Used in Backtracking algorithms like Solving a maze
Problem that involves finding the correct path in a maze.
To reach the final destination, there are several paths. After
following a certain path, if the path chosen is wrong, it is
possible to return to the beginning of that path with the
help of stacks and again trace the correct path.
Infix and Postfix Expressions
An infix expression is one in which the operator is
placed in between the two operands. Eg : a + b.
11. End
Conversion from infix to postfix :
( X *Y–A) – ( D /F +A) ;
Element Action Stack Output
( Push (
X Print ( X
* Push (* X
Y Print (* XY
- Pop, Print ( XY*
Push (-
A Print (- XY*A
) Pop,Print, ( XY*A-
Pop Empty
- Push - XY*A-
( Push -( XY*A-
D Print -( XY*A-D
/ Push -(/ XY*A-D
F Print -(/ XY*A-DF
1. a+((b+c)+(d+e)*f)/g
2. (a-b)*(c/d)+e
3. ((a+b)*c/d+e^f)/g
Evaluation of a Postfix expression
Let the postfix expression end with a ;
Algorithm:
1. Read an element from the infix expression.
2. If element is an operand then PUSH the element to stack and
go to step 1.
3. If element is an operator then POP operand 1 from stack
POP operand 2 from stack
Perform the desired operation
Push the result to stack
Go to step 1.
4. If element is a “;” then POP the result from stack and print result
else go to step 1.
5. End.
Evaluate : 10 15 - 25 5 / + ;
Element Action Stack
10 Push 10
15 Push 10 15
- Pop(15) Pop(10)
Compute (10 – 15) Push( -5) -5
25 Push -5 25
5 Push -5 25 5
/ Pop(5) Pop(25)
Compute ( 25/ 5) Push ( 5 ) -5 5
+ Pop (5) Pop(-5)
Compute (-5+5) Push( 0 ) 0
; Pop result = 0 empty
Evaluate the Postfix Expression given
below
6 12 2 * 3 / 5 3 * - +