Upload
duane-higgins
View
216
Download
0
Embed Size (px)
Citation preview
Basic Data Structures
Stacks
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
R A I LAR
R A I L IAR
R A I LL
IAR
• The Word is now in the stack.
• Now empty the Stack .
LIAR
L L
IAR
L IIAR
L I A
AR
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 operandsPostfix Infix
5 4 + 5 + 4
5 4 + 3 * (5 + 4) * 3
5 4 + 9 6 - * (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 4 + 9 6 - *
5 is a number, place it on the stack
5
Evaluate
5 4 + 9 6 - *
4 is a number, place it on the stack
45
Evaluate
5 4 + 9 6 - *
+ is an operand
•Pop two numbers
•Apply Operand
45
45 + = 9
Evaluate
5 4 + 9 6 - *Put the result back onto the stack
95 4+ = 9
Evaluate
5 4 + 9 6 - *
9 is a number, place it on the stack
99
Evaluate
5 4 + 9 6 - *
6 is a number, place it on the stack
69
9
Evaluate
5 4 + 9 6 - *
- is an operand
• Pop two numbers
• Apply Operand
9
69
69 - = 3
Evaluate
5 4 + 9 6 - *- is an operand
Put the result back onto the stack
969 - = 3
3
Evaluate
5 4 + 9 6 - *
93
* is an operand
Pop two numbers
Apply Operand
39 * = 27
Evaluate
5 4 + 9 6 - *
27
* is an operand
Pop two numbers
Apply Operand
39 * = 27
Evaluate
5 4 + 9 6 - *No more tokens
in the string
• Pop the final answer
27
5 4 + 9 6 - *= (5 + 4) * (9 - 6)= 27