Download presentation
Presentation is loading. Please wait.
Published byDuane Higgins Modified over 9 years ago
1
Basic Data Structures Stacks
2
A collection of objects Objects can be inserted into or removed from the collection at one end (top) First-in-last-out
3
Stack Applications: Reversing a Word RAIL LIAR
4
Empty Stack Start from an empty stack Insert the word RAIL into the stack
5
R A I L R
6
A R
7
I A R
8
L I A R
9
The Word is now in the stack. Now empty the Stack. L I A R
10
L L I A R
11
L I I A R
12
L I A A R
13
L I A R R
14
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
15
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);
16
Evaluate Postfix Expressions Operator comes after the operands PostfixInfix 5 4 +5 + 4 5 4 + 3 *(5 + 4) * 3 5 4 + 9 6 - *(5 + 4) * (9 - 6)
17
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)
18
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
19
Evaluate 5 4 + 9 6 - * 5 is a number, place it on the stack 5
20
Evaluate 5 4 + 9 6 - * 4 is a number, place it on the stack 4 5
21
Evaluate 5 4 + 9 6 - * + is an operand Pop two numbers Apply Operand 4 5 4 5 + = 9
22
Evaluate 5 4 + 9 6 - * Put the result back onto the stack 9 5 4 + = 9
23
Evaluate 5 4 + 9 6 - * 9 is a number, place it on the stack 9 9
24
Evaluate 5 4 + 9 6 - * 6 is a number, place it on the stack 6 9 9
25
Evaluate 5 4 + 9 6 - * - is an operand Pop two numbers Apply Operand 9 6 9 6 9 - = 3
26
Evaluate 5 4 + 9 6 - * - is an operand Put the result back onto the stack 9 6 9 - = 3 3
27
Evaluate 5 4 + 9 6 - * 9 3 * is an operand Pop two numbers Apply Operand 3 9 * = 27
28
Evaluate 5 4 + 9 6 - * 27 * is an operand Pop two numbers Apply Operand 3 9 * = 27
29
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.