Lecture 09 - Applications of Stacks
Lecture 09 - Applications of Stacks
Md Zahidul Islam
Computer Sciece & Engineering Discipline
[email protected]
O UTLINE
Application of stack
Application of stack
O BJECTIVES
P OLISH NOTATIONS
I NFIX TO POSTFIX
I NFIX TO POSTFIX
Start with an infix expression and scan the expression from let
to right:
Step 1 When we get an operand we add it to the postfix expression
Step 2 When we get an opening parentheses we push it on the stack
Step 3 When we get a closing parenthesis we pop the stack and add the symbols to the
postfix expression until we get the opening parenthesis on to the stack
Step 4 When an operator is encountered
I We peek the stack and check the precedence of the operator and the
peeked operator
I If the peeked operator has the same or higher precedence, then we pop
and add the peeked operator to the postfix expression
I Step 4 continues until we peek an operator which has less precedence
than the operator encountered in the infix expression.
Step 5 We push the operator on to the stack
Step 6 If the stack is not empty after we reach the end of the expression, we pop the
stack and add the operators to the postfix expression
Application of stack
A N EXAMPLE
I (A ∗ B − (C/D$E))
Application of stack
A N EXAMPLE
I (A ∗ B − (C/D$E))
Symbol scanned Stack Postfix expression
( (
A ( A
∗ (, ∗ A
B (, ∗ AB
− (, − AB∗
( (, −, ( AB∗
C (, −, ( AB ∗ C
/ (, −, (, / AB ∗ C
D (, −, (, / AB ∗ CD
$ (, −, (, /, $ AB ∗ CD
E (, −, (, /, $ AB ∗ CD
) (, − AB ∗ C D $, /
) AB ∗ CD$/−
I 6 + (2 ∗ 3)
= 6 + 6 = 12
Application of stack
I 6 + (2 ∗ 3)
= 6 + 6 = 12
I 623 ∗ +
Application of stack
I 6 + (2 ∗ 3)
= 6 + 6 = 12
I 623 ∗ +
1. Scan P from left to right and repeat steps 2, 3 and 4 for each element of P.
2. If an operand is encountered, push it on stack.
3. If an operator opr is encountered,
a. Set, op2 = s.pop()
op1 = s.pop();
b. Perform, result = op1 opr op2;
c. Push result back onto stack
[End of if]
[End of step 2 loop]
4. Set value equal to the top element on stack
5. Exit
Application of stack
A N EXAMPLE
I 623 + −3 ∗ 12 + $
Application of stack
A N EXAMPLE
I 623 + −3 ∗ 12 + $
Symb op1 op2 result Stack
6 6
2 6, 2
3 6, 2, 3
+ 2 3 5 6, 5
− 6 5 1 1
3 1, 3
∗ 1 3 3 3
1 3, 1
2 3, 1, 2
+ 1 2 3 3, 3
$ 3 3 27 27
Application of stack
Thank you!!!
Solve ProblemSet05.