Stacks can be used for evaluating expressions. * Stacks use postfix expressions * Algorithm for evaluating a post fix expression using a stack While there are tokens in the expression do get the next token if the token is an operator then retrieve and pop correct number of operands // first off the stack is the last operand do the operation and store results back on the stack else push the token on the stack top of the stack has final answer 7 5 + 7 + 5 = 12 8 9 + 9 8 7 + 10 * + / 8 + 9 = 17 8 + 7 = 15 15 * 10 = 150 9+150=159 17/159=0.107 0.107 12 7 8 9 7 + * 4 4 / * / + = 12.05 * Create a postfix expression from an infix expression * Need to know the priority Operators have different priorities in stack and outside the stack In stack priority In-coming priority ) - - ^ 3 4 *,/ 2 2 +, - 1 1 ( 0 4 while true do if we are at the end of expression then print the stack and quit else if x is an operand then print x else if x = ')' then while top of the stack is not equal to '(' do retrievetop and pop from the stack and print the item retrieved pop '(' from the stack else while the priority of the item on top of the stack is not less than priority of x do retrievetop and pop from the stack and print the item retrieved push x on the top of the stack end {while} X + C + U * Y^9 * (T + W * (7 + 8)) + A (9+8)*6+((8+9)*7+8)*5 9 8 + 6 * 8 9 + 7 * 8 +5 *+ X C + U Y 9 ^ * T W 7 8 + * + * + A +