You are on page 1of 12

EC-211 DATA STRUCTURES

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

Evaluating a Postfix Expression


Each operator in a postfix expression refers to the previous two operands in the expression. Each time we reach an operand we push it onto a stack. When we reach an operator, its operands will be the top two elements on the stack. We then pop these two elements, perform the indicated operation on them, and push the result on the stack. In the end, the result of the expression is left as the only element in the stack, which is popped and returned as the result of evaluation

Algorithm for Evaluating a Postfix Expression


opndstk=the empty stack; //scan the input string one element a time into symb while (not end of input) { symb=next input character; if (symb is an operand) push(opndstk, symb); else { //symb is an operator opnd2=pop(opndstk); opnd1=pop(opndstk); value=result of applying symb to opnd1 and opnd2; push(opndstk, value); } //end else } //end while return (pop(opndstk));

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

Converting an Expression from Infix to Postfix


opstk=the empty stack; while (not end of input) { symb=next input character; if (symb is an operand) add symb to the postfix string else { while (!empty(opstk) && (operator at top of the greater than or equal symb)) { topsymb=pop(opstk); add topsymb to the postfix string; } push(opstk, symb); } //end else } //end while //output any remaining operator while (!empty(opstk) { topsymb=pop(opstk); add topsymb to the postfix string; } //end while

stack has precedence

Example
Convert to Postfix: A+B*C
Symb A Postfix string A opstk

+ B * C

A AB AB ABC ABC* ABC*+

+ + +* +* +

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); }

You might also like