Basic Data Structures Stacks
A collection of objects Objects can be inserted into or removed from the collection at one end (top) First-in-last-out
Stack Applications: Reversing a Word RAIL LIAR
Empty Stack Start from an empty stack Insert the word RAIL into the stack
R A I L R
A R
I A R
L I A R
The Word is now in the stack. Now empty the Stack. L I A R
L L I A R
L I I A R
L I A A R
L I A R R
Stack Operations push : push a new item on the top of the stack pop : if the stack is not empty, remove the top item of the stack; not defined if the stack is empty top : if the stack is not empty, read the value of the top item of the stack; not defined if the stack is empty
Practice What’s remained in the stack after the following operations, assuming that at the beginning the stack is empty? push(3); push(5); pop(); top(); push(9);
Evaluate Postfix Expressions Operator comes after the operands PostfixInfix *(5 + 4) * *(5 + 4) * (9 - 6)
Evaluate Postfix: Keep Intermediate Results E.g. the result of (5 + 4) while we calculate (9 - 6) stacks do this! Assumptions: –binary operators only –we can split the expression string into tokens (pieces)
Evaluate Postfix: the Algorithm while there are more tokens in the input string: –if next token is a number, push it onto the stack –if next token is an operand pop two elements off the stack perform the operation stack the result pop final element as answer
Evaluate * 5 is a number, place it on the stack 5
Evaluate * 4 is a number, place it on the stack 4 5
Evaluate * + is an operand Pop two numbers Apply Operand = 9
Evaluate * Put the result back onto the stack = 9
Evaluate * 9 is a number, place it on the stack 9 9
Evaluate * 6 is a number, place it on the stack 6 9 9
Evaluate * - is an operand Pop two numbers Apply Operand = 3
Evaluate * - is an operand Put the result back onto the stack = 3 3
Evaluate * 9 3 * is an operand Pop two numbers Apply Operand 3 9 * = 27
Evaluate * 27 * is an operand Pop two numbers Apply Operand 3 9 * = 27
Evaluate * No more tokens in the string Pop the final answer * = (5 + 4) * (9 - 6) = 27