Professional Documents
Culture Documents
LECTURE 8
STACK APPLICATIONS
Infix, Prefix, and Postfix Expressions Example
Infix: A+B Prefix: +AB Postfix: AB+
Postfix
Example:
Infix: A+(B*C)
Convert to Postfix A+(B*C) =A+(BC*) =ABC*+ which is the required postfix form
Postfix
Example:
Infix: (A+B)*(C-D)
Convert to Postfix (A+B)*(C-D) =(AB+)*(CD-) =AB+CD-* which is the required postfix form
Example
6 2 3 + - 3 8 2 / + *
symb 6 2 opnd1 opnd2 value opndstk 6 6,2
3
+ 3 8 2 / + * 8 3 1 2 4 7 4 7 7 2 6 3 5 5 1
6,2,3
6,5 1 1,3 1,3,8 1,3,8,2 1,3,4 1,7 7
Example
Convert to Postfix: A+B*C
Symb A Postfix string A opstk
+ B * C
+ + +* +* +
Example
Convert to Postfix: A*B+C*D
Symb A * B + C * D Postfix string A A AB AB* AB*C AB*C AB*CD AB*CD* AB*CD*+ opstk
*
* + + +* +* +
CLASS WORK Suppose S is a non-empty stack of integers. Write a main() function that appropriately utilizes calls to push, pop, and empty to remove the bottom element from the stack. Rest of the stack stays the same. Remember, you do not know the number of elements currently present in stack Prototypes of stack functions:
void push( int) int pop(); bool empty();
Solution
void main() { stack T; int element; while (!S.empty()) { element=S.pop(); T.push( element); } element=T.pop(T); while (!T.empty() element=T.pop(); S.push( element); }