C Programming From Problem Analysis to Program Design
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 19: Stacks and Queues
Objectives In this chapter, you will: • Learn about stacks • Examine various stack operations • Learn how to implement a stack as an array • Learn how to implement a stack as a linked list • Discover stack applications • Learn how to use a stack to remove recursion C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2
Objectives (cont'd. ) • Learn about queues • Examine various queue operations • Learn how to implement a queue as an array • Learn how to implement a queue as a linked list • Discover queue applications C++ Programming: From Problem Analysis to Program Design, Fifth Edition 3
Stacks • Stack: list of homogenous elements – Addition and deletion occur only at one end, called the top of the stack • Example: in a cafeteria, the second tray can be removed only if first tray has been removed – Last in first out (LIFO) data structure • Operations: – Push: to add an element onto the stack – Pop: to remove an element from the stack C++ Programming: From Problem Analysis to Program Design, Fifth Edition 4
Stacks (cont’d. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 5
Stacks (cont’d. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 6
Stack Operations • In the abstract class stack. ADT: – initialize. Stack – is. Empty. Stack – is. Full. Stack – push – top – pop C++ Programming: From Problem Analysis to Program Design, Fifth Edition 7
Implementation of Stacks as Arrays • First element can go in first array position, the second in the second position, etc. • The top of the stack is the index of the last element added to the stack • Stack elements are stored in an array • Stack element is accessed only through top • To keep track of the top position, use a variable called stack. Top C++ Programming: From Problem Analysis to Program Design, Fifth Edition 8
Implementation of Stacks as Arrays (cont'd. ) • Because stack is homogeneous – You can use an array to implement a stack • Can dynamically allocate array – Enables user to specify size of the array • The class stack. Type implements the functions of the abstract class stack. ADT C++ Programming: From Problem Analysis to Program Design, Fifth Edition 9
Implementation of Stacks as Arrays (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 10
Implementation of Stacks as Arrays (cont'd. ) • C++ arrays begin with the index 0 – Must distinguish between: • The value of stack. Top • The array position indicated by stack. Top • If stack. Top is 0, the stack is empty • If stack. Top is nonzero, the stack is not empty – The top element is given by stack. Top - 1 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 11
Implementation of Stacks as Arrays (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 12
Initialize Stack C++ Programming: From Problem Analysis to Program Design, Fifth Edition 13
Empty Stack • If stack. Top is 0, the stack is empty C++ Programming: From Problem Analysis to Program Design, Fifth Edition 14
Full Stack • The stack is full if stack. Top is equal to max. Stack. Size C++ Programming: From Problem Analysis to Program Design, Fifth Edition 15
Push • Store the new. Item in the array component indicated by stack. Top • Increment stack. Top • Must avoid an overflow C++ Programming: From Problem Analysis to Program Design, Fifth Edition 16
Push (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 17
Return the Top Element C++ Programming: From Problem Analysis to Program Design, Fifth Edition 18
Pop • Simply decrement stack. Top by 1 • Must check for underflow condition C++ Programming: From Problem Analysis to Program Design, Fifth Edition 19
Pop (cont’d. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 20
Pop (cont’d. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 21
Copy Stack C++ Programming: From Problem Analysis to Program Design, Fifth Edition 22
Constructor and Destructor C++ Programming: From Problem Analysis to Program Design, Fifth Edition 23
Constructor and Destructor (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 24
Copy Constructor C++ Programming: From Problem Analysis to Program Design, Fifth Edition 25
Overloading the Assignment Operator (=) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 26
Stack Header File • Place definitions of class and functions (stack operations) together in a file C++ Programming: From Problem Analysis to Program Design, Fifth Edition 27
Programming Example: Highest GPA • Input: program reads an input file with each student’s GPA and name 3. 5 3. 6 2. 7 3. 9 3. 4 Bill John Lisa Kathy Jason David Jack • Output: the highest GPA and all the names associated with the highest GPA C++ Programming: From Problem Analysis to Program Design, Fifth Edition 28
Programming Example: Problem Analysis and Algorithm Design • Read the first GPA and name of the student – This is the highest GPA so far • Read the second GPA and student name – Compare this GPA with highest GPA so far • New GPA is greater than highest GPA so far – Update highest GPA, initialize stack, add to stack • New GPA is equal to the highest GPA so far – Add name to stack • New GPA is smaller than the highest GPA – Discard C++ Programming: From Problem Analysis to Program Design, Fifth Edition 29
Programming Example: Problem Analysis and Algorithm Design (cont’d. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 30
Programming Example: Problem Analysis and Algorithm Design (cont’d. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 31
Linked Implementation of Stacks • Array only allows fixed number of elements • If number of elements to be pushed exceeds array size – Program may terminate • Linked lists can dynamically organize data • In a linked representation, stack. Top is pointer to top element in stack C++ Programming: From Problem Analysis to Program Design, Fifth Edition 32
Linked Implementation of Stacks (cont’d. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 33
Default Constructor • Initializes the stack to an empty state when a stack object is declared – Sets stack. Top to NULL C++ Programming: From Problem Analysis to Program Design, Fifth Edition 34
Empty Stack and Full Stack • In the linked implementation of stacks, the function is. Full. Stack does not apply – Logically, the stack is never full C++ Programming: From Problem Analysis to Program Design, Fifth Edition 35
Initialize Stack C++ Programming: From Problem Analysis to Program Design, Fifth Edition 36
Push • The new. Element is added at the beginning of the linked list pointed to by stack. Top C++ Programming: From Problem Analysis to Program Design, Fifth Edition 37
Push (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 38
Push (cont'd. ) • We do not need to check whether the stack is full before we push an element onto the stack C++ Programming: From Problem Analysis to Program Design, Fifth Edition 39
Return the Top Element C++ Programming: From Problem Analysis to Program Design, Fifth Edition 40
Pop • Node pointed to by stack. Top is removed C++ Programming: From Problem Analysis to Program Design, Fifth Edition 41
Pop (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 42
Pop (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 43
Copy Stack C++ Programming: From Problem Analysis to Program Design, Fifth Edition 44
Copy Stack (cont'd. ) • Notice that this function is similar to the definition of copy. List for linked lists C++ Programming: From Problem Analysis to Program Design, Fifth Edition 45
Constructors and Destructors C++ Programming: From Problem Analysis to Program Design, Fifth Edition 46
Overloading the Assignment Operator (=) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 47
Stack as Derived from the class unordered. Linked. List • Our implementation of push is similar to insert. First (discussed for general lists) – Other functions are similar too: • initialize. Stack and initialize. List • is. Empty. List and is. Empty. Stack • linked. Stack. Type can be derived from linked. List. Type – class linked. List. Type is abstract • Must implement pop as described earlier C++ Programming: From Problem Analysis to Program Design, Fifth Edition 48
Derived Stack (cont’d. ) • unordered. Linked. List. Type is derived from linked. List. Type – Provides the definitions of the abstract functions of the class linked. List. Type • We can derive the linked. Stack. Type from unordered. Linked. List. Type C++ Programming: From Problem Analysis to Program Design, Fifth Edition 49
Application of Stacks: Postfix Expressions Calculator • Infix notation: usual notation for writing arithmetic expressions – The operator is written between the operands – Example: a + b – The operators have precedence • Parentheses can be used to override precedence C++ Programming: From Problem Analysis to Program Design, Fifth Edition 50
Application of Stacks: Postfix Expressions Calculator (cont'd. ) • Prefix (Polish) notation: the operators are written before the operands – Introduced by the Polish mathematician Jan Lukasiewicz • Early 1920 s – The parentheses can be omitted – Example: + a b C++ Programming: From Problem Analysis to Program Design, Fifth Edition 51
Application of Stacks: Postfix Expressions Calculator (cont'd. ) • Reverse Polish notation: the operators follow the operands (postfix operators) – Proposed by the Australian philosopher and early computer scientist Charles L. Hamblin • Late 1950's – Advantage: the operators appear in the order required for computation – Example: a + b * c • In a postfix expression: a b c * + C++ Programming: From Problem Analysis to Program Design, Fifth Edition 52
Application of Stacks: Postfix Expressions Calculator (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 53
Application of Stacks: Postfix Expressions Calculator (cont'd. ) • Postfix notation has important applications in computer science – Many compilers first translate arithmetic expressions into postfix notation and then translate this expression into machine code • Evaluation algorithm: – Scan expression from left to right – When an operator is found, back up to get the operands, perform the operation, and continue C++ Programming: From Problem Analysis to Program Design, Fifth Edition 54
Application of Stacks: Postfix Expressions Calculator (cont'd. ) • Example: 6 3 + 2 * = C++ Programming: From Problem Analysis to Program Design, Fifth Edition 55
Application of Stacks: Postfix Expressions Calculator (cont'd. ) • Symbols can be numbers or anything else: – +, -, *, and / are operators • Pop stack twice and evaluate expression • If stack has less than two elements error – If symbol is =, the expression ends • Pop and print answer from stack • If stack has more than one element error – If symbol is anything else • Expression contains an illegal operator C++ Programming: From Problem Analysis to Program Design, Fifth Edition 56
Application of Stacks: Postfix Expressions Calculator (cont'd. ) • Examples: 7 6 + 3 ; 6 - = • ; is an illegal operator 14 + 2 3 * = • Does not have enough operands for + 14 2 3 + = • Error: stack will have two elements when we encounter equal (=) sign C++ Programming: From Problem Analysis to Program Design, Fifth Edition 57
Application of Stacks: Postfix Expressions Calculator (cont'd. ) • We assume that the postfix expressions are in the following form: #6 #3 + #2 * = – If symbol scanned is #, next input is a number – If the symbol scanned is not #, then it is: • An operator (may be illegal) or • An equal sign (end of expression) • We assume expressions contain only +, -, *, and / operators C++ Programming: From Problem Analysis to Program Design, Fifth Edition 58
Main Algorithm • Pseudocode: • We will write four functions: – evaluate. Expression, evaluate. Opr, discard. Exp, and print. Result C++ Programming: From Problem Analysis to Program Design, Fifth Edition 59
Function evaluate. Expression C++ Programming: From Problem Analysis to Program Design, Fifth Edition 60
Function evaluate. Opr C++ Programming: From Problem Analysis to Program Design, Fifth Edition 61
Function evaluate. Opr (cont’d. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 62
Function discard. Exp • This function is called whenever an error is discovered in the expression C++ Programming: From Problem Analysis to Program Design, Fifth Edition 63
Function print. Result • If the postfix expression contains no errors, the function print. Result prints the result – Otherwise, it outputs an appropriate message • The result of the expression is in the stack and the output is sent to a file C++ Programming: From Problem Analysis to Program Design, Fifth Edition 64
Function print. Result (cont’d. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 65
Removing Recursion: Nonrecursive Algorithm to Print a Linked List Backward • To print the list backward, first we need to get to the last node of the list – Problem: how do we get back to previous node? • Links go in only one direction – Solution: save a pointer to each of the nodes with info 5, 10, and 15 • Use a stack (LIFO) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 66
Removing Recursion: Nonrecursive Algorithm to Print a Linked List Backward (cont’d. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 67
Removing Recursion: Nonrecursive Algorithm to Print a Linked List Backward (cont’d. ) • Let us now execute the following statements: • Output: 20 15 10 5 C++ Programming: From Problem Analysis to Program Design, Fifth Edition 68
Queues • Queue: list of homogeneous elements • Elements are: – Added at one end (the back or rear) – Deleted from the other end (the front) • First In First Out (FIFO) data structure – Middle elements are inaccessible • Example: – Waiting line in a bank C++ Programming: From Problem Analysis to Program Design, Fifth Edition 69
Queue Operations • Some of the queue operations are: – initialize. Queue – is. Empty. Queue – is. Full. Queue – front – back – add. Queue – delete. Queue • Abstract class queue. ADT defines these operations C++ Programming: From Problem Analysis to Program Design, Fifth Edition 70
Implementation of Queues as Arrays • You need at least four (member) variables: – An array to store the queue elements – queue. Front and queue. Rear • To keep track of first and last elements – max. Queue. Size • To specify the maximum size of the queue C++ Programming: From Problem Analysis to Program Design, Fifth Edition 71
Implementation of Queues as Arrays (cont'd. ) • To add an element to the queue: – Advance queue. Rear to next array position – Add element to position pointed by queue. Rear • Example: array size is 100; originally empty C++ Programming: From Problem Analysis to Program Design, Fifth Edition 72
Implementation of Queues as Arrays (cont'd. ) • To delete an element from the queue: – Retrieve element pointed to by queue. Front – Advance queue. Front to next queue element C++ Programming: From Problem Analysis to Program Design, Fifth Edition 73
Implementation of Queues as Arrays (cont'd. ) • Will this queue design work? – Suppose A stands for adding an element to the queue – And D stands for deleting an element from the queue – Consider the following sequence of operations: • AAADADADADA. . . C++ Programming: From Problem Analysis to Program Design, Fifth Edition 74
Implementation of Queues as Arrays (cont'd. ) • The sequence AAADADADADA. . . would eventually set queue. Rear to point to the last array position – Giving the impression that the queue is full C++ Programming: From Problem Analysis to Program Design, Fifth Edition 75
Implementation of Queues as Arrays (cont'd. ) • Solution 1: – When the queue overflows to the rear (i. e. , queue. Rear points to the last array position): • Check value of queue. Front • If value of queue. Front indicates that there is room in the front of the array, slide all of the queue elements toward the first array position • Problem: too slow for large queues • Solution 2: assume that the array is circular C++ Programming: From Problem Analysis to Program Design, Fifth Edition 76
Implementation of Queues as Arrays (cont'd. ) • To advance the index in a (logically) circular array: C++ Programming: From Problem Analysis to Program Design, Fifth Edition 77
Implementation of Queues as Arrays (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 78
Implementation of Queues as Arrays (cont'd. ) • Case 1: C++ Programming: From Problem Analysis to Program Design, Fifth Edition 79
Implementation of Queues as Arrays (cont'd. ) • Case 2: C++ Programming: From Problem Analysis to Program Design, Fifth Edition 80
Implementation of Queues as Arrays (cont'd. ) • Problem: – Figures 19 -32 b and 19 -33 b have identical values for queue. Front and queue. Rear – However, the former represents an empty queue, whereas the latter shows a full queue • Solution? C++ Programming: From Problem Analysis to Program Design, Fifth Edition 81
Implementation of Queues as Arrays (cont'd. ) • Solution 1: keep a count – Incremented when a new element is added to the queue – Decremented when an element is removed – Initially, set to 0 – Very useful if user (of queue) frequently needs to know the number of elements in the queue • We will implement this solution C++ Programming: From Problem Analysis to Program Design, Fifth Edition 82
Implementation of Queues as Arrays (cont'd. ) • Solution 2: let queue. Front indicate index of the array position preceding the first element – queue. Rear still indicates index of last one – Queue empty if: • queue. Front == queue. Rear – Slot indicated by queue. Front is reserved • Queue can hold 99 (not 100) elements – Queue full if the next available space is the reserved slot indicated by queue. Front C++ Programming: From Problem Analysis to Program Design, Fifth Edition 83
Implementation of Queues as Arrays (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 84
Empty Queue and Full Queue C++ Programming: From Problem Analysis to Program Design, Fifth Edition 85
Initialize Queue C++ Programming: From Problem Analysis to Program Design, Fifth Edition 86
Front • Returns the first element of the queue C++ Programming: From Problem Analysis to Program Design, Fifth Edition 87
Back • Returns the last element of the queue C++ Programming: From Problem Analysis to Program Design, Fifth Edition 88
add. Queue C++ Programming: From Problem Analysis to Program Design, Fifth Edition 89
delete. Queue C++ Programming: From Problem Analysis to Program Design, Fifth Edition 90
Constructors and Destructors C++ Programming: From Problem Analysis to Program Design, Fifth Edition 91
Constructors and Destructors (cont'd. ) • The array to store the queue elements is created dynamically – When the queue object goes out of scope, the destructor simply deallocates the memory occupied by the array C++ Programming: From Problem Analysis to Program Design, Fifth Edition 92
Linked Implementation of Queues • Array size is fixed: only a finite number of queue elements can be stored in it • The array implementation of the queue requires array to be treated in a special way – Together with queue. Front and queue. Rear • The linked implementation of a queue simplifies many of the special cases of the array implementation – In addition, the queue is never full C++ Programming: From Problem Analysis to Program Design, Fifth Edition 93
Linked Implementation of Queues (cont'd. ) • Elements are added at one end and removed from the other – We need to know the front of the queue and the rear of the queue • Two pointers: queue. Front and queue. Rear C++ Programming: From Problem Analysis to Program Design, Fifth Edition 94
Empty and Full Queue • The queue is empty if queue. Front is NULL • The queue is never full C++ Programming: From Problem Analysis to Program Design, Fifth Edition 95
Initialize Queue • Initializes queue to an empty state – Must remove all the elements, if any C++ Programming: From Problem Analysis to Program Design, Fifth Edition 96
add. Queue C++ Programming: From Problem Analysis to Program Design, Fifth Edition 97
front and back Operations C++ Programming: From Problem Analysis to Program Design, Fifth Edition 98
delete. Queue C++ Programming: From Problem Analysis to Program Design, Fifth Edition 99
Default Constructor C++ Programming: From Problem Analysis to Program Design, Fifth Edition 100
Queue Derived from the class unordered. Linked. List. Type • The linked implementation of a queue is similar to the implementation of a linked list created in a forward manner – add. Queue is similar to insert. First – initialize. Queue is like initialize. List – is. Empty. Queue is similar to is. Empty. List – delete. Queue can be implemented as before – queue. Front is the same as first – queue. Rear is the same as last C++ Programming: From Problem Analysis to Program Design, Fifth Edition 101
Queue Derived from the class unordered Linked. List. Type (cont'd. ) • We can derive the class to implement the queue from linked. List. Type – Abstract class: does not implement all the operations • However, unordered. Linked. List. Type is derived from linked. List. Type – Provides the definitions of the abstract functions of the linked. List. Type – Therefore, we can derive linked. Queue. Type from unordered. Linked. List. Type C++ Programming: From Problem Analysis to Program Design, Fifth Edition 102
Application of Queues: Simulation • Simulation: a technique in which one system models the behavior of another system • Computer simulations using queues as the data structure are called queuing systems C++ Programming: From Problem Analysis to Program Design, Fifth Edition 103
Designing a Queuing System • Server: the object that provides the service • Customer: the object receiving the service • Transaction time: service time, or the time it takes to serve a customer • Model: system that consists of a list of servers and a waiting queue holding the customers to be served – Customer at front of queue waits for the next available server C++ Programming: From Problem Analysis to Program Design, Fifth Edition 104
Designing a Queuing System (cont'd. ) • We need to know: – Number of servers – Expected arrival time of a customer – Time between the arrivals of customers – Number of events affecting the system • Performance of system depends on: – How many servers are available – How long it takes to serve a customer – How often a customer arrives C++ Programming: From Problem Analysis to Program Design, Fifth Edition 105
Designing a Queuing System (cont'd. ) • If it takes too long to serve a customer and customers arrive frequently, then more servers are needed • System can be modeled as a time-driven simulation • Time-driven simulation: the clock is a counter – The passage of, say, one minute can be implemented by incrementing the counter by 1 – Simulation is run for a fixed amount of time C++ Programming: From Problem Analysis to Program Design, Fifth Edition 106
Customer C++ Programming: From Problem Analysis to Program Design, Fifth Edition 107
Server C++ Programming: From Problem Analysis to Program Design, Fifth Edition 108
Server List • A server list is a set of servers – At a given time, a server is either free or busy C++ Programming: From Problem Analysis to Program Design, Fifth Edition 109
Waiting Customers Queue • When a customer arrives, he/she goes to the end of the queue • When a server becomes available, the customer at front of queue leaves to conduct the transaction • After each time unit, the waiting time of each customer in the queue is incremented by 1 • We can use queue. Type but must add the operation of incrementing the waiting time C++ Programming: From Problem Analysis to Program Design, Fifth Edition 110
Waiting Customers Queue (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 111
Main Program • Algorithm: – Declare and initialize the variables – Main loop (see next slide) – Print results C++ Programming: From Problem Analysis to Program Design, Fifth Edition 112
Main Program (cont'd. ) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 113
Summary • Stack: items are added/deleted from one end – Last In First Out (LIFO) data structure – Operations: push, pop, initialize, destroy, check for empty/full stack – Can be implemented as array or linked list – Middle elements should not be accessed • Postfix notation: operators are written after the operands (no parentheses needed) C++ Programming: From Problem Analysis to Program Design, Fifth Edition 114
Summary (cont'd. ) • Queue: items are added at one end and removed from the other end – First In First Out (FIFO) data structure – Operations: add, remove, initialize, destroy, check if queue is empty/full – Can be implemented as array or linked list – Middle elements should not be accessed – Restricted versions of arrays and linked lists C++ Programming: From Problem Analysis to Program Design, Fifth Edition 115
- Slides: 115