Download presentation
Presentation is loading. Please wait.
1
Chapter 7 Queues
2
The Abstract Data Type Queue
A queue New items enter at the back, or rear, of the queue Items leave from the front of the queue First-in, first-out (FIFO) property The first item inserted into a queue is the first item to leave © 2005 Pearson Addison-Wesley. All rights reserved
3
The Abstract Data Type Queue
Queues Are appropriate for many real-world situations Example: A line to buy a movie ticket Have applications in computer science Example: A request to print a document A simulation A study to see how to reduce the wait involved in an application © 2005 Pearson Addison-Wesley. All rights reserved
4
The Abstract Data Type Queue
ADT queue operations Create an empty queue Destroy a queue Determine whether a queue is empty Add a new item to the queue Remove the item that was added earliest Retrieve the item that was added earliest © 2005 Pearson Addison-Wesley. All rights reserved
5
The Abstract Data Type Queue
bool isEmpty() const; // Determines whether the queue is empty. // Precondition: None. // Postcondition: Returns true if the queue // is empty; otherwise returns false. © 2005 Pearson Addison-Wesley. All rights reserved
6
The Abstract Data Type Queue
void enqueue(QueueItemType newItem); // Inserts an item at the back of a queue. // Precondition: newItem is the item to be // inserted. // Postcondition: If the insertion is // successful, newItem is at the back of the // queue. © 2005 Pearson Addison-Wesley. All rights reserved
7
The Abstract Data Type Queue
void dequeue() throw(QueueException); // Dequeues the front of a queue. // Precondition: None. // Postcondition: If the queue is not empty, // the item that was added to the queue // earliest is deleted. // Exception: Throws QueueException if the // queue is empty. © 2005 Pearson Addison-Wesley. All rights reserved
8
The Abstract Data Type Queue
void dequeue(QueueItemType& queueFront) throw(QueueException); // Retrieves and deletes the front of a queue // Precondition: None. // Postcondition: If the queue is not empty, // queueFront contains the item that was // added to the queue earliest, and the item // is deleted. // Exception: Throws QueueException if the // queue is empty. © 2005 Pearson Addison-Wesley. All rights reserved
9
The Abstract Data Type Queue
void getFront(QueueItemType& queueFront)const throw(QueueException); // Retrieves the item at the front of a queue // Precondition: None. // Postcondition: If the queue is not empty, // queueFront contains the item that was // added to the queue earliest. // Exception: Throws QueueException if the // queue is empty. © 2005 Pearson Addison-Wesley. All rights reserved
10
Reading a String of Characters
A queue can retain characters in the order in which they are typed aQueue.createQueue() while (not end of line) { Read a new character ch aQueue.enqueue(ch) } Once the characters are in a queue, the system can process them as necessary © 2005 Pearson Addison-Wesley. All rights reserved
11
Converting Digits in a Queue into a Decimal Integer
// get first digit, ignoring any leading blanks do { aQueue.dequeue(ch) } while (ch is blank) // compute n from digits in queue n = 0 done = false n = 10 * n + integer that ch represents if (!aQueue.isEmpty()) else done = true } while (!done and ch is a digit) © 2005 Pearson Addison-Wesley. All rights reserved
12
Recognizing Palindromes
A palindrome A string of characters that reads the same from left to right as its does from right to left To recognize a palindrome, a queue can be used in conjunction with a stack A stack reverses the order of occurrences A queue preserves the order of occurrences © 2005 Pearson Addison-Wesley. All rights reserved
13
Recognizing Palindromes
A nonrecursive recognition algorithm for palindromes As you traverse the character string from left to right, insert each character into both a queue and a stack Compare the characters at the front of the queue and the top of the stack © 2005 Pearson Addison-Wesley. All rights reserved
14
Recognizing Palindromes
Figure 7.3 The results of inserting a string into both a queue and a stack © 2005 Pearson Addison-Wesley. All rights reserved
15
Implementations of the ADT Queue
An array-based implementation Possible implementations of a pointer-based queue A linear linked list with two external references A reference to the front A reference to the back A circular linked list with one external reference © 2005 Pearson Addison-Wesley. All rights reserved
16
A Pointer-Based Implementation
Figure 7.4 A pointer-based implementation of a queue: (a) a linear linked list with two external pointers b) a circular linear linked list with one external pointer © 2005 Pearson Addison-Wesley. All rights reserved
17
A Pointer-Based Implementation
Figure 7.5 Inserting an item into a nonempty queue © 2005 Pearson Addison-Wesley. All rights reserved
18
A Pointer-Based Implementation
Figure 7.6 Inserting an item into an empty queue: a) before insertion; b) after insertion © 2005 Pearson Addison-Wesley. All rights reserved
19
A Pointer-Based Implementation
Figure 7.7 Deleting an item from a queue of more than one item © 2005 Pearson Addison-Wesley. All rights reserved
20
A Pointer-Based Implementation
typedef desired-type-of-queue-item QueueItemType; class Queue{ public: Queue(); // default constructor Queue(const Queue& Q); // copy constructor ~Queue(); // destructor // Queue operations: bool isEmpty() const; void enqueue(QueueItemType newItem); void dequeue() throw(QueueException); void dequeue(QueueItemType& queueFront) throw(QueueException); void getFront(QueueItemType& queueFront) const throw(QueueException); private: // The queue is implemented as a linked list with one external // pointer to the front of the queue and a second external // pointer to the back of the queue. struct QueueNode{ QueueItemType item; QueueNode *next; }; QueueNode *backPtr; QueueNode *frontPtr; © 2005 Pearson Addison-Wesley. All rights reserved
21
A Pointer-Based Implementation
// default constructor Queue::Queue() : backPtr(NULL), frontPtr(NULL){ } // copy constructor Queue::Queue(const Queue& Q){ // Implementation left as an exercise (Exercise 4) © 2005 Pearson Addison-Wesley. All rights reserved
22
A Pointer-Based Implementation
// destructor Queue::~Queue(){ while (!isEmpty()) dequeue(); assert ((backPtr == NULL) && (frontPtr == NULL)); } © 2005 Pearson Addison-Wesley. All rights reserved
23
A Pointer-Based Implementation
bool Queue::isEmpty() const { return backPtr == NULL; } © 2005 Pearson Addison-Wesley. All rights reserved
24
A Pointer-Based Implementation
void Queue::enqueue(QueueItemType newItem){ // create a new node QueueNode *newPtr = new QueueNode; // set data portion of new node newPtr->item = newItem; newPtr->next = NULL; // insert the new node if (isEmpty()) // insertion into empty queue frontPtr = newPtr; else // insertion into nonempty queue backPtr->next = newPtr; backPtr = newPtr; // new node is at back } © 2005 Pearson Addison-Wesley. All rights reserved
25
A Pointer-Based Implementation
void Queue::dequeue() throw(QueueException){ if (isEmpty()) throw QueueException("empty queue"); else{ // queue is not empty; remove front QueueNode *tempPtr = frontPtr; if (frontPtr == backPtr){ // special case frontPtr = NULL; backPtr = NULL; } else frontPtr = frontPtr->next; tempPtr->next = NULL; // defensive strategy delete tempPtr; © 2005 Pearson Addison-Wesley. All rights reserved
26
A Pointer-Based Implementation
void Queue::dequeue(QueueItemType& queueFront) throw(QueueException){ if (isEmpty()) throw QueueException("empty queue"); else{ // queue is not empty; retrieve front queueFront = frontPtr->item; dequeue(); // delete front } © 2005 Pearson Addison-Wesley. All rights reserved
27
A Pointer-Based Implementation
void Queue::getFront(QueueItemType& queueFront)const throw(QueueException){ if (isEmpty()) throw QueueException("empty queue"); else // queue is not empty; retrieve front queueFront = frontPtr->item; } © 2005 Pearson Addison-Wesley. All rights reserved
28
An Array-Based Implementation
Figure 7.8 a) A naive array-based implementation of a queue; b) rightward drift can cause the queue to appear full © 2005 Pearson Addison-Wesley. All rights reserved
29
An Array-Based Implementation
A circular array eliminates the problem of rightward drift A problem with the circular array implementation front and back cannot be used to distinguish between queue-full and queue-empty conditions © 2005 Pearson Addison-Wesley. All rights reserved
30
An Array-Based Implementation
Figure 7.11b (a) front passes back when the queue becomes empty; (b) back catches up to front when the queue becomes full © 2005 Pearson Addison-Wesley. All rights reserved
31
An Array-Based Implementation
To detect queue-full and queue-empty conditions Keep a count of the queue items To initialize the queue, set front to 0 back to MAX_QUEUE – 1 count to 0 © 2005 Pearson Addison-Wesley. All rights reserved
32
An Array-Based Implementation
Inserting into a queue back = (back+1) % MAX_QUEUE; items[back] = newItem; ++count; Deleting from a queue front = (front+1) % MAX_QUEUE; --count; © 2005 Pearson Addison-Wesley. All rights reserved
33
An Array-Based Implementation
const int MAX_QUEUE = maximum-size-of-queue; typedef desired-type-of-queue-item QueueItemType; class Queue{ public: Queue(); // default constructor // copy constructor and destructor are // supplied by the compiler // Queue operations: bool isEmpty() const; void enqueue(QueueItemType newItem) throw(QueueException); void dequeue() throw(QueueException); void dequeue(QueueItemType& queueFront) throw(QueueException); void getFront(QueueItemType& queueFront) const throw(QueueException); private: QueueItemType items[MAX_QUEUE]; int front; int back; int count; }; © 2005 Pearson Addison-Wesley. All rights reserved
34
An Array-Based Implementation
// default constructor Queue::Queue():front(0), back(MAX_QUEUE-1), count(0){ } © 2005 Pearson Addison-Wesley. All rights reserved
35
An Array-Based Implementation
bool Queue::isEmpty() const { return (count == 0); } © 2005 Pearson Addison-Wesley. All rights reserved
36
An Array-Based Implementation
void Queue::enqueue(QueueItemType newItem) throw(QueueException){ if (count == MAX_QUEUE) throw QueueException("queue full"); else{ // queue is not full; insert item back = (back+1) % MAX_QUEUE; items[back] = newItem; ++count; } © 2005 Pearson Addison-Wesley. All rights reserved
37
An Array-Based Implementation
void Queue::dequeue() throw(QueueException){ if (isEmpty()) throw QueueException("empty queue"); else { // queue is not empty; remove front front = (front+1) % MAX_QUEUE; --count; } © 2005 Pearson Addison-Wesley. All rights reserved
38
An Array-Based Implementation
void Queue::dequeue(QueueItemType& queueFront) throw(QueueException) { if (isEmpty()) throw QueueException("empty queue"); else{ // queue is not empty; // retrieve and remove front queueFront = items[front]; front = (front+1) % MAX_QUEUE; --count; } © 2005 Pearson Addison-Wesley. All rights reserved
39
An Array-Based Implementation
void Queue::getFront(QueueItemType& queueFront) const throw(QueueException) { if (isEmpty()) throw QueueException("empty queue"); else // queue is not empty; retrieve front queueFront = items[front]; } © 2005 Pearson Addison-Wesley. All rights reserved
40
An Array-Based Implementation
Variations of the array-based implementation Use a flag isFull to distinguish between the full and empty conditions Declare MAX_QUEUE + 1 locations for the array items, but use only MAX_QUEUE of them for queue items © 2005 Pearson Addison-Wesley. All rights reserved
41
An Array-Based Implementation
Figure 7.12 A more efficient circular implementation: a) a full queue; b) an empty queue © 2005 Pearson Addison-Wesley. All rights reserved
42
An Implementation That Uses the ADT List
If the item in position 1 of a list aList represents the front of the queue, the following implementations can be used dequeue() aList.remove(1) getFront(queueFront) aList.retrieve(1, queueFront) © 2005 Pearson Addison-Wesley. All rights reserved
43
An Implementation That Uses the ADT List
If the item at the end of the list represents the back of the queue, the following implementations can be used enqueue(newItem) aList.insert(getLength() + 1, newItem) © 2005 Pearson Addison-Wesley. All rights reserved
44
An Implementation That Uses the ADT List
#include "ListP.h" // ADT list operations typedef ListItemType QueueItemType; class Queue { public: Queue(); // default constructor Queue(const Queue& Q); // copy constructor ~Queue(); // destructor // Queue operations: bool isEmpty() const; void enqueue(QueueItemType newItem) throw(QueueException); void dequeue() throw(QueueException); void dequeue(QueueItemType& queueFront) throw(QueueException); void getFront(QueueItemType& queueFront) const private: List aList; }; © 2005 Pearson Addison-Wesley. All rights reserved
45
An Implementation That Uses the ADT List
// default constructor Queue::Queue() { } // copy constructor Queue::Queue(const Queue& Q): aList(Q.aList){ © 2005 Pearson Addison-Wesley. All rights reserved
46
An Implementation That Uses the ADT List
// destructor Queue::~Queue() { } © 2005 Pearson Addison-Wesley. All rights reserved
47
An Implementation That Uses the ADT List
bool Queue::isEmpty() const { return (aList.getLength() == 0); } © 2005 Pearson Addison-Wesley. All rights reserved
48
An Implementation That Uses the ADT List
void Queue::enqueue(QueueItemType newItem) throw(QueueException) { try { aList.insert(aList.getLength()+1, newItem); } catch (ListException e) { throw QueueException("cannot enqueue item"); © 2005 Pearson Addison-Wesley. All rights reserved
49
An Implementation That Uses the ADT List
void Queue::dequeue() throw(QueueException) { if (aList.isEmpty()) throw QueueException("empty queue"); else aList.remove(1); } © 2005 Pearson Addison-Wesley. All rights reserved
50
An Implementation That Uses the ADT List
void Queue::dequeue(QueueItemType& queueFront) throw(QueueException) { if (aList.isEmpty()) throw QueueException("empty queue"); else { aList.retrieve(1, queueFront); aList.remove(1); } © 2005 Pearson Addison-Wesley. All rights reserved
51
An Implementation That Uses the ADT List
void Queue::getFront(QueueItemType& queueFront) const throw(QueueException) { if (!aList.isEmpty()) throw QueueException("empty queue"); else aList.retrieve(1, queueFront); } © 2005 Pearson Addison-Wesley. All rights reserved
52
Comparing Implementations
Fixed size versus dynamic size A statically allocated array Prevents the enqueue operation from adding an item to the queue if the array is full A resizable array or a reference-based implementation Does not impose this restriction on the enqueue operation © 2005 Pearson Addison-Wesley. All rights reserved
53
Comparing Implementations
Pointer-based implementations A linked list implementation More efficient The ADT list implementation Simpler to write © 2005 Pearson Addison-Wesley. All rights reserved
54
A Summary of Position-Oriented ADTs
List Stack Queue Stacks and queues Only the end positions can be accessed Lists All positions can be accessed © 2005 Pearson Addison-Wesley. All rights reserved
55
A Summary of Position-Oriented ADTs
Stacks and queues are very similar Operations of stacks and queues can be paired off as createStack and createQueue Stack isEmpty and queue isEmpty push and enqueue pop and dequeue Stack getTop and queue getFront © 2005 Pearson Addison-Wesley. All rights reserved
56
A Summary of Position-Oriented ADTs
ADT list operations generalize stack and queue operations getLength insert remove retrieve © 2005 Pearson Addison-Wesley. All rights reserved
57
Application: Simulation
A technique for modeling the behavior of both natural and human-made systems Goal Generate statistics that summarize the performance of an existing system Predict the performance of a proposed system Example A simulation of the behavior of a bank © 2005 Pearson Addison-Wesley. All rights reserved
58
Application: Simulation
Figure A bank line at time a) 0; b) 12 c) 20; d) 38 © 2005 Pearson Addison-Wesley. All rights reserved
59
Application: Simulation
An event-driven simulation Simulated time is advanced to time of the next event Events are generated by a mathematical model that is based on statistics and probability © 2005 Pearson Addison-Wesley. All rights reserved
60
Application: Simulation
A time-driven simulation Simulated time is advanced by a single time unit The time of an event is determined randomly and compared with a simulated clock © 2005 Pearson Addison-Wesley. All rights reserved
61
Application: Simulation
Time Event 20 Customer 1 enters bank and begins transaction 22 Customer 2 enters bank and stands at end of line 23 Customer 3 enters bank and stands at end of line 25 Customer 1 departs; customer 2 begins transaction 29 Customer 2 departs; customer 3 begins transaction 30 Customer 4 enters bank and stands at end of line 31 Customer 3 departs; customer 4 begins transaction 34 Customer 4 departs Suppose that we have the following data Arrival time Transaction time 20 5 22 4 23 2 30 3 © 2005 Pearson Addison-Wesley. All rights reserved
62
Application: Simulation
The bank simulation is concerned with Arrival events External events: the input file specifies the times at which the arrival events occur Departure events Internal events: the simulation determines the times at which the departure events occur © 2005 Pearson Addison-Wesley. All rights reserved
63
Application: Simulation
An event list is needed to implement an event-driven simulation An event list Keeps track of arrival and departure events that will occur but have not occurred yet Contains at most one arrival event and one departure event The arrival events are specified in the input file in ascending time order © 2005 Pearson Addison-Wesley. All rights reserved
64
Application: Simulation
As customers arrive, they go to the back of the line We will use a queue to represent the line of customers in the bank The current customer, who is at the front of the line, is being served You remove this customer from the system next © 2005 Pearson Addison-Wesley. All rights reserved
65
Application: Simulation
Time Action bankQueue (front to back) anEventList (beginning to end) Read file, place event in anEventList (empty) 20 Update anEventList and bankQueue: Customer 1 enters bank Customer 1 begins transaction; create departure event 22 Update anEventList and bankQueue: Customer 2 enters bank 23 Update anEventList and bankQueue: Customer 3 enters bank 25 Update anEventList and bankQueue: Customer 1 departs Customer 2 begins transaction, create departure event … complete this trace as an exercise A 20 5 20 5 D 25 20 5 A D 25 20 5 22 4 D 25 20 5 22 4 A D 25 20 5 22 4 23 2 D 25 20 5 22 4 23 2 D 25 A 30 3 22 4 23 2 A 30 3 22 4 23 2 D 29 A 30 3 © 2005 Pearson Addison-Wesley. All rights reserved
66
Summary The definition of the queue operations gives the ADT queue first-in, first-out (FIFO) behavior A pointer-based implementation of a queue uses either A circular linked list A linear linked list with a head reference and a tail reference © 2005 Pearson Addison-Wesley. All rights reserved
67
Summary A circular array eliminates the problem of rightward drift in an array-based implementation Distinguishing between the queue-full and queue-empty conditions in a circular array Count the number of items in the queue Use a isFull flag Leave one array location empty © 2005 Pearson Addison-Wesley. All rights reserved
68
Summary Simulations In a time-driven simulation
Time is advanced by a single time unit In an event-driven simulation Time is advanced to the time of the next event To implement an event-driven simulation, you maintain an event list that contains events that have not yet occurred © 2005 Pearson Addison-Wesley. All rights reserved
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.