Date post: | 11-Jan-2016 |
Category: |
Documents |
Upload: | laurence-stephen-jenkins |
View: | 213 times |
Download: | 0 times |
1
Stacks
Chapter 4
2
Introduction
• Consider a program to model a switching yard– Has main line and siding– Cars may be shunted, removed at any time
3
Introduction
• What data type can be used to model the operation of the siding– The first car in must be the last car out– The last car in must be the first car out
• This is often called a LIFO structure or a
STACK
4
A Stack
• Definition: – An ordered collection of data items– Can be accessed at only one end (the top)
• Operations:– construct a stack (usually empty)– check if it is empty– Push: add an element to the top– Top: retrieve the top element– Pop: remove the top element
5
Building a Stack
Design the Class
• Identify operations needed to manipulate "real-world" objects modeled by class.
• Operations are described: – Independent of class implementation.– Independent of any specific representation of
object • we have no idea of what data members will be
available
6
Stack Operations
• Construction: – Initializes an empty stack.
• Empty operation: – Determines if stack contains any values
• Push operation: – Modifies a stack by adding a value to top of
stack
• Top operation: – Retrieves the value at the top of the stack
7
Stack Operations
• Pop operation: – Modifies a stack by removing the top value of
the stack
To help with debugging, add early on:
• Output: – Displays all the elements stored in the stack
8
Possible Implementation
• Stack is a collection of values• Use an array with the top of the stack at
position 0.• Example Push 75, Push 89, Push 64, Pop
• Consider what might be awkward about this implementation?
0 1 2 3 4
0 1 2 3 4
75Push 75
0 1 2 3 4
89Push 89
750 1 2 3 4
89
Push 64
75
64 0 1 2 3 4
89Pop
75
9
Alternative Implementation
• Instead of modeling a stack of plates, model a stack of books
10
Alternative Implementation
• Keep the bottom of stack at position 0.
• Maintain a "pointer" myTop to the top of the stack.
• Note: no moving of any elements
7589
43210
Push 75 Push 89
7589
Push 64
75
64
Pop43210
43210
43210
43210
8975
64
myTopmyTop
myTopmyTop
myTop
myTop = -1
myTop = 0 myTop = 1 myTop = 2myTop = 1
11
Data Members for the Stack
• We need– an array data member to hold the stack
elements– an integer to indicate the top of the stack
• Declaration of the array:
arrayElementType myArray [ARRAYCAPACITY];
12
Data Members for the Stack
• Problems– the type of the array– the capacity of the stack
• Solution– use typedef mechanism
typedef int StackElement;– for the capacityconst int STACK_CAPACITY = 128;
• Declaration becomesStackElement myArray [STACK_CAPACITY];
13
Observations
• When stack for different type needed– specify typedef whatever StackElement;
• Placing typedef and STACK_CAPACITY outside class makes them– easy to find when they need changing– accessible throughout the class and in any file
that #includes Stack.h– qualification not needed
14
Observations
• Placing typedef and STACK_CAPACITY inside the class as public members– can be accessed outside the class– qualification required Stack::STACK_CAPACITY
• If placed as private data members– probably declared as static data member
static const int STACK_CAPACITY = 128;– all instances of Stack have access to this
attribute– but they do not have their own copy
15
Observations
• Alternative to use of typedef– A template to build a Stack class– Type element left unspecified– Element type passed as special kind of
parameter at compile timetemplate class
16
Declaration#ifndef STACK#define STACK
const int STACK_CAPACITY = 128;typedef int StackElement;
class Stack{/***** Function Members *****/public: . . ./***** Data Members *****/private: StackElement myArray[STACK_CAPACITY]; int myTop;}; // end of class declaration. . .#endif
Declared outside the class declaration
Declared outside the class declaration
17
Application of Stacks
Consider events when a function begins execution
• Activation record (or stack frame) is created
• Stores the current environment for that function.
• Contents:
Parameters
Contents of registers, return address
Local variables
Temp storage
18
Run-time Stack
• Functions may call other functions– interrupt their own execution
• Must store the activation records to be recovered– system then reset when first function resumes
execution
• This algorithm must have LIFO behavior
• Structure used is the run-time stack
19
Use of Run-time Stack
When a function is called …
• Copy of activation record pushed onto run-time stack
• Arguments copied into parameter spaces
• Control transferred to starting address of body of function
20
Use of Run-time Stack
When function terminates• Run-time stack popped
– Removes activation record of terminated function
– exposes activation record of previously executing function
• Activation record used to restore environment of interrupted function
• Interrupted function resumes execution
21
Application of Stacks
Consider the arithmetic statement in the assignment statement:
x = a * b + c
Compiler must generate machine instructions
1. LOAD a
2. MULT b
3. ADD c
4. STORE x
Note: this is "infix" notation
The operators are between the operands
Note: this is "infix" notation
The operators are between the operands
22
RPN or Postfix Notation
• Most compilers convert an expression in infix notation to postfix – the operators are written after the operands
• So a * b + c becomes a b * c +
• Advantage:– expressions can be written without
parentheses
23
Postfix and Prefix Examples
INFIX RPN (POSTFIX) PREFIX
A + BA * B + CA * (B + C)A - (B - (C - D))A - B - C - D
A B * C +A B C + *A B C D---A B-C-D-
+ * A B C* A + B C-A-B-C D---A B C D
A B + + A B
Prefix : Operators come before the operands
Prefix : Operators come before the operands
24
2 7 -1 - * 2 7 -1 - *
Evaluating RPN Expressions
"By hand" (Underlining technique):
1. Scan the expression from left to right to find an operator.
2. Locate ("underline") the last two preceding operands and combine them using this operator.
3. Repeat until the end of the expression is reached.
Example: 2 3 4 + 5 6 - - *
2 3 4 + 5 6 - - *
2 8 * 2 8 * 16
2 7 5 6 - - * 2 7 5 6 - - *
25
Evaluating RPN ExpressionsBy using a stack algorithm1. Initialize an empty stack2. Repeat the following until the end of the
expression is encountereda) Get the next token (const, var, operator) in the
expressionb) Operand – push onto stack
Operator – do the followingi. Pop 2 values from stackii. Apply operator to the two valuesiii. Push resulting value back onto stack
3. When end of expression encountered, value of expression is the (only) number left in stack
Note: if only 1 value on stack, this is an invalid
RPN expression
Note: if only 1 value on stack, this is an invalid
RPN expression
26
Evaluating RPN Expressions
• Try this example using the stack algorithm: 2 3 4 + 5 6 - - *
4
3
2
1
0
4
3
2
1
0
4
3
2
1
0
4
3
2
1
0
27
Sample RPN EvaluationExample: 2 3 4 + 5 6 - - *
Push 2Push 3Push 4Read +
Pop 4, Pop 3, Push 7Push 5Push 6Read -
Pop 6, Pop 5, Push -1Read -
Pop -1, Pop 7, Push 8Read *
Pop 8, Pop 2, Push 16
234
2756
27-1
28
16
3 + 4 = 7
5 - 6 = -1
7 - -1 = 8
2 * 8 = 16
28
Unary minus causes problems
Example: 5 3 - -
5 3 - - 5 -3 - 8
5 3 - - 2 -
-2
Use a different symbol:
5 3 ~ -
OR
5 3 - ~
Observation
29
Converting Infix to RPN
By hand: Represent infix expression as an expression tree:
A * B + C
+
C*
A B
A * (B + C) ((A + B) * C) / (D - E)
*
A+
B C C
A B
D E
*
+
/
-
x y
x y
30
C
A B
D E
*
+
/
-
Traverse the tree in Left-Right-Parent order (postorder) to get RPN:
C
A B
D E
*
+
/
-
Traverse tree in Parent-Left-Right order (preorder) to get prefix:
Traverse tree in Left-Parent-Right order (inorder) to get infix — must insert ()'s
A B + C * D E - /
- D E
(A + B)( * C) /( )(D - E) C
A B
D E
*
+
/
-
/ * + A B C
31
By hand: "Fully parenthesize-move-erase" method:
1. Fully parenthesize the expression.
2. Replace each right parenthesis by the corresponding operator.
3. Erase all left parentheses.
Examples:
A * B + C
((A B * C + A B * C +
A * (B + C)
(A (B C + * A B C + *
Exercise:
((A + B) * C) / (D - E)
((A * B) + C) (A * (B + C) )
Another RPN Conversion Method
32
Stack Algorithm
1. Initialize an empty stack of operators
2. While no error && !end of expressiona) Get next input "token" from infix expression
b) If token is …
i. "(" : push onto stack
ii. ")" : pop and display stack elements until "(" occurs, do not display it
const, var, arith operator, left or right paren
const, var, arith operator, left or right paren
33
Stack Algorithm
iii. operator if operator has higher priority than top of stack push token onto stackelse pop and display top of stack repeat comparison of token with top of stack
iv. operand display it
3. When end of infix reached, pop and display stack items until empty
Note: Left parenthesis in stack has lower priority
than operators
Note: Left parenthesis in stack has lower priority
than operators
34
(-
/
Example:Push ( OutputDisplay APush +Display BPush *Display CRead )
Pop *, Display *, Pop +, Display +, Pop (
Push /Push (Display D Push -Push (Display EPush -Display FRead )
Pop -, Display -, Pop (Read ) Pop -, Display -, Pop (Pop /, Display /
(+*
(+
(-(-
(
(A+B*C)/(D-(E-F))
A
ABC
AB
ABC*ABC*+
ABC*+D
ABC*+DE
ABC*+DEF
ABC*+DEF-
ABC*+DEF--
(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))
/
/ABC*+DEF--/
(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))(A+B*C)/(D-(E-F))