Download presentation
Presentation is loading. Please wait.
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: Operations: 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: Empty operation: Push operation:
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: To help with debugging, add early on:
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? 1 2 3 4 75 Push 75 1 2 3 4 89 Push 89 75 1 2 3 4 89 Push 64 75 64 1 2 3 4 89 Pop 75 1 2 3 4
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 myTop myTop myTop myTop myTop myTop = -1 myTop = 0 myTop = 1 myTop = 2 myTop = 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 capacity const int STACK_CAPACITY = 128; Declaration becomes StackElement 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 time template class
16
Declared outside the class 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
17
Contents of registers, return address
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 LOAD a MULT b ADD c STORE x 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 + B A * B + C A * (B + C) A - (B - (C - D)) A - B - C - D A B + + A B A B * C + + * A B C A B C + * * A + B C -A-B-C D A B C D--- A B-C-D- ---A B C D Prefix : Operators come before the operands
24
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 8 * ® 2 8 * ® 16
25
Evaluating RPN Expressions
By using a stack algorithm Initialize an empty stack Repeat the following until the end of the expression is encountered Get the next token (const, var, operator) in the expression Operand – push onto stack Operator – do the following Pop 2 values from stack Apply operator to the two values Push resulting value back onto stack 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
26
Evaluating RPN Expressions
Try this example using the stack algorithm: * 4 3 2 1 4 3 2 1 4 3 2 1 4 3 2 1
27
Sample RPN Evaluation Example: 2 3 4 + 5 6 - - * 4 3 2 6 5 7 2 -1 7 2
Push 2 Push 3 Push 4 Read + Pop 4, Pop 3, Push 7 Push 5 Push 6 Read - Pop 6, Pop 5, Push -1 Pop -1, Pop 7, Push 8 Read * Pop 8, Pop 2, Push 16 4 3 2 6 3 + 4 = 7 5 7 2 5 - 6 = -1 -1 7 2 = 8 8 2 2 * 8 = 16 16
28
Observation Unary minus causes problems Example: 5 3 - - 5 3 - -
® ® 8 ® 2 - ® -2 OR Use a different symbol: 5 3 ~ - 5 3 - ~
29
Converting Infix to RPN
By hand: Represent infix expression as an expression tree: A * B + C A * (B + C) ((A + B) * C) / (D - E) * A + C C A B D E * + / - * A B + B C D x y x D y
30
Traverse the tree in Left-Right-Parent order (postorder) to get RPN:
C A B D E * + / - Traverse the tree in Left-Right-Parent order (postorder) to get RPN: A B + C * D E - / Traverse tree in Parent-Left-Right order (preorder) to get prefix: C A B D E * + / - - D E / * + A B C C A B D E * + / - Traverse tree in Left-Parent-Right order (inorder) to get infix — must insert ()'s ( ) / ( * C) (A + B) (D - E)
31
Another RPN Conversion Method
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 + (A (B C + * A B C + * Exercise: ((A + B) * C) / (D - E)
32
const, var, arith operator, left or right paren
Stack Algorithm Initialize an empty stack of operators While no error && !end of expression Get next input "token" from infix expression If token is … "(" : push onto stack ")" : pop and display stack elements until "(" occurs, do not display it const, var, arith operator, left or right paren
33
Note: Left parenthesis in stack has lower priority than operators
Stack Algorithm Note: Left parenthesis in stack has lower priority than operators operator if operator has higher priority than top of stack push token onto stack else pop and display top of stack repeat comparison of token with top of stack operand display it When end of infix reached, pop and display stack items until empty
34
Example: (A+B*C)/(D-(E-F)) (A+B*C)/(D-(E-F)) (A+B*C)/(D-(E-F))
Push ( Output Display A Push + Display B Push * Display C Read ) Pop *, Display *, Pop +, Display +, Pop ( Push / Push ( Display D Push - Display E Display F Pop -, Display -, Pop ( Pop /, Display / (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)) (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 + AB ( ABC + ( ABC* ( ABC*+ - ABC*+D ( - ABC*+DE ( / ABC*+DEF ( - / ABC*+DEF- / ABC*+DEF-- ABC*+DEF--/
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.