90 likes | 194 Views
CSE 246 Data Structures and Algorithms. Spring2011 Lecture#12. Evaluating Postfix. Each operator in a postfix expression refers to the previous two operands. Each time we read an operand, we push it on a stack.
E N D
CSE 246Data Structures and Algorithms Spring2011 Lecture#12
Evaluating Postfix • Each operator in a postfix expression refers to the previous two operands. • Each time we read an operand, we push it on a stack. • When we reach an operator, we pop the two operands from the top of the stack, apply the operator and push the result back on the stack. Quratulain
Postfix Expression evaluation Algorithm In english:Scan the Postfix string from left to right. • Initialize an empty stack. • If the scanned character is an operand, add it to the stack. If the scanned character is an operator, there will be at least two operands in the stack. • If the scanned character is an Operator, then we store the top most element of the stack(topStack) in a variable temp. Pop the stack. Now evaluate topStack(Operator)temp. Let the result of this operation be retVal. Pop the stack and Push retVal into the stack. • Repeat this step till all the characters are scanned. • After all characters are scanned, we will have only one element in the stack. Return topStack as result Quratulain
Algorithm for postfix evalution Opndstk = the emty stack; While (not end of input) { Symb = next input character; If (symb is an operand) Push(opndstk,symb); Else { Opnd2=pop(opndstk); Opnd1=pop(opndstk); Value = result of applying symb to opnd1 and opnd2; Push(opndstk, value); } } Return (pop(opndstk)); Quratulain
A Stack Interface in Java • The stack data structure is included as a "built-in" class in the java.util package of Java. • it is instructive to learn how to design and implement a stack "from scratch.“ • Implementing an abstract data type in Java involves two steps • Define interface • Define exceptions for any error conditions that can arise. • Provide a concrete class that implements the methods of the interface associated with that ADT. Quratulain
Stack interface public interface Stack <E> { public int size(); public booleanisEmpty(); public E top() throws EmptyStackException; public void push( E element); public E pop() throws EmptyStackException; } Quratulain
Implementing a Stack with a Generic Linked List Left as homework Quratulain