Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stacks CHAPTER 7 MAY 21, 2015 Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005.

Similar presentations


Presentation on theme: "Stacks CHAPTER 7 MAY 21, 2015 Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005."— Presentation transcript:

1 Stacks CHAPTER 7 MAY 21, 2015 Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 1

2 Linked Lists with Head Nodes  Dual algorithms can be reduced to one  Create a "dummy" head node  Serves as predecessor holding actual first element  Thus even an empty list has a head node 2

3 Circular Linked Lists  Set the link in last node to point to first node  Each node now has both predecessor and successor  Insertions, deletions now easier  Special consideration required for insertion to empty list, deletion from single item list 3

4 Doubly-Linked Lists  Bidirectional lists  Nodes have data part, forward and backward link  Facilitates both forward and backward traversal  Requires pointers to both first and last nodes 4

5 Comparing List With Other Containers  Note : list does not support direct access  does not have the subscript operator [ ] 5 PropertyArray vector deque list Direct/random access ( [] ) Excellent Excellent Good NA Sequential access Excellent Excellent Good Excellent Insert/delete at front Poor Poor Excellent Excellent Insert/delete in middle Poor Poor Poor Excellent Insert/delete at end Excellent Excellent Excellent Excellent Overheadlowestlowlow/mediumhigh

6 The STL list Class Template  A sequential container  Optimized for insertion and erasure at arbitrary points in the sequence.  Implemented as a circular doubly-linked list with head node. 6

7 The STL list Memory Management When a node is allocated 1. If there is a node on the free list, allocate it. This is maintained as a linked stack 2. If the free list is empty: a) Call the heap manager to allocate a block of memory (a "buffer", typically 4K) b) Carve it up into pieces of size required for a node of a list 7

8 Multiply-Ordered Lists  Ordered linked list  Nodes arranged so data items are in ascending/descending order  Straightforward when based on one data field  However, sometimes necessary to maintain links with a different ordering  Possible solution  Separate ordered linked lists – but wastes space  Better approach  Single list  Multiple links 8

9 Sparse Matrices  Note the resulting representation of the matrix 9 A =

10 Generalized Lists  Examples so far have had atomic elements  The nodes are not themselves lists  Generalized List: a list where the elements themselves are lists  Consider a linked list of strings  The strings themselves can be linked lists of characters 10 This is an example of a generalized list

11 Chapter Contents 7.1 Introduction to Stacks 7.2 Designing and Building a Stack Class – Array-Based 7.3 Linked Stacks 7.4 Use of Stacks in Function Calls 7.5 Case Study: Postfix (RPN) Notation 11

12 Chapter Objectives  Study a stack as an ADT  Build a dynamic-array-based implementation of stacks  Build a linked-implementation of stacks  Show how a run-time stack is used to store information during function calls  (Optional) Study postfix notation and see how stacks are used to convert expressions from infix to postfix and how to evaluate postfix expressions 12

13 Introduction to Stacks  Consider a card game with a discard pile  Discards always placed on the top of the pile  Players may retrieve a card only from the top  This is a stack 13

14 Introduction to Stacks  A stack is a last-in-first-out (LIFO) data structure  Adding an item  Referred to as pushing it onto the stack  Removing an item  Referred to as popping it from the stack 14

15 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 15

16 Example Program  Consider a program to do base conversion of a number (ten to two) 16

17 Selecting Storage Structure  Model with an array  Let position 0 be top of stack  Problem … consider pushing and popping  Requires much shifting 17

18 Selecting Storage Structure  A better approach is to let position 0 be the bottom of the stack  Thus our design will include  An array to hold the stack elements  An integer to indicate the top of the stack 18

19 Dynamic Array to Store Stack Elements  Same issues regarding static arrays for stacks as for lists  Can run out of space if stack set too small  Can waste space if stack set too large  As before, we demonstrate a dynamic array implementation to solve the problems 19

20 Stack Class 20

21 Dynamic Array to Store Stack Elements  Class Destructor needed  Avoids memory leak  Deallocates array allocated by constructor 21

22 Dynamic Array to Store Stack Elements  Copy Constructor needed for  Initializations  Passing value parameter  Returning a function value  Creating a temporary storage value  Provides for deep copy 22

23 Dynamic Array to Store Stack Elements  Assignment operator  Again, deep copy needed  Copies member-by-member, not just address  Can use the same code used for the copy constructor 23

24 Further Considerations  What if dynamic array initially allocated for stack is too small?  Could terminate  Better to replace with larger array  Creating a larger array  Allocate larger array  Use loop to copy elements into new array  Delete old array  Point _items variable at this new array 24

25 Further Considerations  How long does it take to move the stack to a larger array?  How large should the new array be?  Incremental strategy: increase size by constant c  Doubling strategy: double the size 25 O(n)O(n)

26 Comparison of the Strategies  We will analyze the total time T(n) needed to perform a series of n push operations  We assume that we start with an empty stack represented by an array of size 1  We call the amortized time of a push operation the average time taken by a push over the series of operations, i.e., T(n)/n 26

27 Incremental Strategy Analysis  We replace the array k = n / c times  k = O(n) since c is a constant  The total time T(n) of a series of n push operations is proportional to 27

28 Incremental Strategy Analysis  The amortized time A(n) of a push operation is 28

29 Doubling Strategy Analysis  We replace the array k = log 2 n times  The total time T(n) of a series of n push operations is proportional to  The amortized time of a push operation is 29

30 Linked Stacks  Another alternative to allowing stacks to grow as needed  Linked list stack needs only one data member  Pointer myTop  Nodes allocated (but not part of stack class) 30

31 Implementing Linked Stack Operations  Constructor  Simply assign null pointer to myTop  Empty  Check for myTop == null  Push  Insertion at beginning of list  Top  Return data to which myTop points 31

32 Implementing Linked Stack Operations  Pop  Delete first node in the linked list ptr = myTop; myTop = myTop->next; delete ptr;  Output  Traverse the list for (ptr = myTop; ptr != 0; ptr = ptr- >next) out data << endl; 32

33 Implementing Linked Stack Operations  Destructor  Must traverse list and deallocate nodes  Note need to keep track of ptr->next before calling delete ptr;  Copy Constructor  Traverse linked list, copying each into new node  Attach new node to copy 33

34 Implementing Linked Stack Operations  Assignment operator  Similar to copy constructor  Must first rule out self assignment  Must destroy list in stack being assigned a new value 34

35 Stack Summary Stack Operation Complexity for Different Implementations 35 Array Fixed-Size Array Expandable (doubling strategy) List Singly- Linked Pop() O(1) Push(o)O(1)O(n) Worst Case O(1) Best Case O(1) Average Case O(1) Top()O(1) Size(), isEmpty()O(1)

36 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: 36

37 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 37

38 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 38

39 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 39

40 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 40 Note: this is "infix" notation The operators are between the operands Note: this is "infix" notation The operators are between the operands

41 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 41

42 Postfix and Prefix Examples INFIX RPN (POSTFIX) PREFIX A + B A * B + C A * (B + C) A - (B - (C - D)) A - B - C - D 42 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

43 Evaluating RPN Expressions 43  2 7 5 6 - - *  2 7 -1 - *  2 7 -1 - *  "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 *  16

44 Evaluating RPN Expressions By using a stack algorithm 1. Initialize an empty stack 2. Repeat the following until the end of the expression is encountered a) Get the next token (const, var, operator) in the expression b) Operand – push onto stack Operator – do the following i. Pop 2 values from stack ii. Apply operator to the two values iii. Push resulting value back onto stack 3. When end of expression encountered, value of expression is the (only) number left in stack 44 Note: if only 1 value on stack, this is an invalid RPN expression

45 Evaluation of Postfix  Note the changing status of the stack 45

46 Converting Infix to RPN 46 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

47 ( )( * C)(D - E) 47 C AB D E * + / - Traverse the tree in Left-Right-Parent order (postorder) to get RPN: C AB 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 AB+C*DE-/ - D E (A + B) / C AB D E * + / - / * + A B C

48 Another RPN Conversion Method 48 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) )

49 Stack Algorithm 1. Initialize an empty stack of operators 2. While no error && !end of expression a) 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 49 const, var, arith operator, left or right paren

50 Stack Algorithm iii. 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 iv. operand display it 3. When end of infix reached, pop and display stack items until empty 50 Note: Left parenthesis in stack has lower priority than operators


Download ppt "Stacks CHAPTER 7 MAY 21, 2015 Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005."

Similar presentations


Ads by Google