Stacks - Infix To Postfix
Stacks - Infix To Postfix
K
MODULE 3
AGENDA
2
• Basic Definition of a Stack
• Array Implementation of a Stack
• Basic Operations – Push(), POP(), IsEmpty()
• Applications
• Balancing parenthesis
• Recursive function Calls
• Expression Evaluation
• Infix, Prefix and Postfix Notations
• Infix to Prefix and Postfix conversion
• Postfix Evaluation
What is a Stack ? 3
BASIC DEFINITION
4
• Push Operation The process of putting a new data element onto stack is
known as a Push Operation.
• Push operation involves a series of steps
• Step 1 − Checks if the stack is full.
• Step 2 − If the stack is full, produces an error and exit.
• Step 3 − If the stack is not full, increments top to point next empty space.
• Step 4 − Adds data element to the stack location, where top is pointing.
• Step 5 − Returns success.
8
35
Algorithm
if stack is full
top 35 return null
endif
top 36
36
31
31 top ← top + 1
32 stack[top] ← data
32
34
34 end procedure
POP OPERATION
• 9
Accessing the content while removing it from the stack, is known as a Pop Operation.
• In an array implementation of pop() operation, the data element is not actually
removed, instead top is decremented to a lower position in the stack to point to the
next value.
• But in linked-list implementation, pop() actually removes data element and deallocates
memory space.
• A Pop operation may involve the following steps
• Step 1 − Checks if the stack is empty.
• Step 2 − If the stack is empty, produces an error and exit.
• Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
• Step 4 − Decreases the value of top by 1.
• Step 5 − Returns success.
35 10
Algorithm
35 35 end procedure
STACK APPLICATIONS
11
• Balancing parenthesis
• Recursive function Calls
• Expression Evaluation
• Reversing a list
• Conversion of an infix expression into a postfix expression
• Evaluation of a postfix expression
• Towers of Hanoi
BALANCING PARENTHESIS 12
Expression { (a + b) * (a – b) }
Algorithm
14
•After complete traversal of input string, If stack is empty then input expression
is a Valid expression otherwise Invalid.
EXPRESSION EVALUATION
15
• Representation of algebraic expression
• Infix notation
• Prefix or polish notation
• Postfix or reverse polish notation
A A
* A
*
B
AB
*
STACK
18
EVALUATING POSTFIX NOTATION 19
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
END Procedure
STOP
FOR PRACTICE 25
1. A – (B / C + (D % E * F) / G)* H)
2. (A – B / C) * (A / K – L)
3. ((A – (B + C)) * D) / (E + F)
4. A + B * C + (D * E + F) * G
5. A + (B * C – (D / E + F) * G) * H