Chapter 7: Queues QUEUE IMPLEMENTATIONS QUEUE APPLICATIONS CS 240 44.

Slides:



Advertisements
Similar presentations
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
Advertisements

Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
Queues CS 308 – Data Structures. What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: –Elements are added at.
CS 240Chapter 7 - QueuesPage 29 Chapter 7 Queues The queue abstract data type is essentially a list using the FIFO (first-in-first-out) policy for adding.
1 Queues – Chapter 3 A queue is a data structure in which all additions are made at one end called the rear of the queue and all deletions are made from.
Queues CS 3358 – Data Structures. What is a queue? It is an ordered group of homogeneous items of elements. Queues have two ends: – Elements are added.
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
LINKED QUEUES P LINKED QUEUE OBJECT Introduction Introduction again, the problem with the previous example of queues is that we are working.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 18 Stacks.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 18: Stacks And Queues.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Queue Overview Queue ADT Basic operations of queue
CS 240Chapter 6 - StacksPage 21 Chapter 6 Stacks The stack abstract data type is essentially a list using the LIFO (last-in-first-out) policy for adding.
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
Chapter 7 Queues. © 2005 Pearson Addison-Wesley. All rights reserved7-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Queues CS-240 & CS-341 Dick Steflik. Queues First In, First Out operation - FIFO As items are added they are chronologically ordered, items are removed.
Queues CS-240 & CS-341 Dick Steflik. Queues First In, First Out operation - FIFO As items are added they are chronologically ordered, items are removed.
5 Linked Structures. 2 Definition of Stack Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and.
1 Queues (Walls & Mirrors - Chapter 7). 2 Overview The ADT Queue Linked-List Implementation of a Queue Array Implementation of a Queue.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
CS 1031 Queues Definition of a Queue Examples of Queues Design of a Queue Class Different Implementations of the Queue Class.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2b. Simple Containers: The Queue.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Data Structures Using C++ 2E Chapter 8 Queues. Data Structures Using C++ 2E2 Objectives Learn about queues Examine various queue operations Learn how.
Data Structures Using Java1 Chapter 7 Queues. Data Structures Using Java2 Chapter Objectives Learn about queues Examine various queue operations Learn.
Lab 7 Queue ADT. OVERVIEW The queue is one example of a constrained linear data structure. The elements in a queue are ordered from least recently added.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 7: Queues Data Abstraction & Problem Solving with C++
Data Structures Using C++
1 Queues. 2 Queue Which of the following cases use similar structures? Cars lined up at a tollgate Cars on a 4-lane highway Customers at supermarket check-out.
Queues CS 302 – Data Structures Sections 5.3 and 5.4.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
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)
UNIT II Queue. Syllabus Contents Concept of queue as ADT Implementation using linked and sequential organization. – linear – circular queue Concept –
CE 221 Data Structures and Algorithms
Chapter 7 Queues Introduction Queue applications Implementations.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 Queues Chapter 4. 2 Objectives You will be able to Describe a queue as an ADT. Build a dynamic array based implementation of a queue ADT.
1 Linked Multiple Queues. 2 A real world example. Not in the book. Sometimes we have a fixed number of items that move around among a fixed set of queues.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
CS 240Chapter 10 – TreesPage Chapter 10 Trees The tree abstract data type provides a hierarchical to the representation of certain types of relationships.
114 3/30/98 CSE 143 Collection ADTs [Chapter 4] /30/98 Collection ADTs  Many standard ADTs are for collections  Data structures that manage groups.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 18: Stacks and Queues.
1 Data Structures and Algorithms Queue. 2 The Queue ADT Introduction to the Queue data structure Designing a Queue class using dynamic arrays Linked Queues.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2b. Simple Containers: The Queue.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Abstract Data Types Queues Dale Roberts, Lecturer
Review Array Array Elements Accessing array elements
CSCE 210 Data Structures and Algorithms
18 Chapter Stacks and Queues
CS505 Data Structures and Algorithms
Chapter 18: Stacks and Queues.
CC 215 Data Structures Queue ADT
C++ Plus Data Structures
Stack and Queue APURBO DATTA.
Chapter 4 Linked Lists
Chapter 16-2 Linked Structures
Queues.
Chapter 19: Stacks and Queues.
Queues.
Pointers & Dynamic Data Structures
Queues.
Queues Definition of a Queue Examples of Queues
CSCS-200 Data Structure and Algorithms
Data Structures & Programming
Presentation transcript:

Chapter 7: Queues QUEUE IMPLEMENTATIONS QUEUE APPLICATIONS CS

CS The queue abstract data type is essentially a list using the FIFO (first-in-first-out) policy for adding and removing elements. The principal queue operations: Create an empty queue. Copy an existing queue. Destroy a queue. Determine whether a queue is empty. Add a new element to a queue. Remove the least recently added element from a queue.

CS Queue Implementation Alternatives An Array Implementation Positives Avoids pointers (uses front & rear indices)  Negatives × Wraparound is needed to avoid false overflows × Size must be declared in advance A Linked List Implementation Positives Dynamically allocates exactly the right amount of memory Wraparound is circumvented  Negatives × Our friendly neighborhood pointers           

CS Array Implementation of Queue // Class declaration file: Queue.h // Array implementation of the queue ADT. #ifndef QUEUE_H typedef int elementType; const MAX_QUEUE_SIZE = 200; class queue { public: // Class constructors queue(); queue(const queue &q); // Member functions bool isEmpty(); void enqueue(const elementType &item); elementType dequeue(); protected: // Data members int front, rear, length; elementType list[MAX_QUEUE_SIZE]; // Member function bool isFull(); }; #define QUEUE_H #endif // Class declaration file: Queue.h // Array implementation of the queue ADT. #ifndef QUEUE_H typedef int elementType; const MAX_QUEUE_SIZE = 200; class queue { public: // Class constructors queue(); queue(const queue &q); // Member functions bool isEmpty(); void enqueue(const elementType &item); elementType dequeue(); protected: // Data members int front, rear, length; elementType list[MAX_QUEUE_SIZE]; // Member function bool isFull(); }; #define QUEUE_H #endif // Class implementation file: queue.cpp // Array implementation of the queue ADT. #include "Queue.h" #include // Default constructor: Make empty queue // queue:: queue() { front = 0; rear = MAX_QUEUE_SIZE – 1; length = 0; } // Copy constructor: Make copy of queue. // queue:: queue(const queue &q) { int index; front = q.front; rear = q.rear; length = q.length; for (int i = 0; i < length; i++) { index = (i + q.front) % MAX_QUEUE_SIZE; list[index] = q.list[index]; } // Class implementation file: queue.cpp // Array implementation of the queue ADT. #include "Queue.h" #include // Default constructor: Make empty queue // queue:: queue() { front = 0; rear = MAX_QUEUE_SIZE – 1; length = 0; } // Copy constructor: Make copy of queue. // queue:: queue(const queue &q) { int index; front = q.front; rear = q.rear; length = q.length; for (int i = 0; i < length; i++) { index = (i + q.front) % MAX_QUEUE_SIZE; list[index] = q.list[index]; }

CS // isEmpty function: signals if *this is empty queue. // bool queue:: isEmpty() { return (length == 0); } // Enqueue function; inserts a new item into the // // rear of queue *this (if there's enough room). // void queue:: enqueue(const elementType &item) { assert(!isFull()); rear = (rear+1) % MAX_QUEUE_SIZE; list[rear] = item; length++; } // Dequeue function; remove the item at the // // front of queue *this (if there's one there). // elementType queue:: dequeue() { elementType item; assert(!isEmpty()); item = list[front]; front = (front+1) % MAX_QUEUE_SIZE; length--; return item; } // isFull function; returns boolean value indicating // // if *this is a full queue (w.r.t. the array). // bool queue:: isFull() { return (length == MAX_QUEUE_SIZE); } // isEmpty function: signals if *this is empty queue. // bool queue:: isEmpty() { return (length == 0); } // Enqueue function; inserts a new item into the // // rear of queue *this (if there's enough room). // void queue:: enqueue(const elementType &item) { assert(!isFull()); rear = (rear+1) % MAX_QUEUE_SIZE; list[rear] = item; length++; } // Dequeue function; remove the item at the // // front of queue *this (if there's one there). // elementType queue:: dequeue() { elementType item; assert(!isEmpty()); item = list[front]; front = (front+1) % MAX_QUEUE_SIZE; length--; return item; } // isFull function; returns boolean value indicating // // if *this is a full queue (w.r.t. the array). // bool queue:: isFull() { return (length == MAX_QUEUE_SIZE); } Insert from the rear (with wraparound) Insert from the rear (with wraparound) Remove from the front (with wraparound) Remove from the front (with wraparound)

CS Linked List Implementation of Queue // Class declaration file: Queue.h // Linked List implementation of queue ADT. #ifndef QUEUE_H #include "LinkedList.h" class queue: protected LinkedList { public: // Class constructors queue(); queue(const queue &q); // Member functions bool isEmpty(); void enqueue(const elementType &item); elementType dequeue(); protected: // Data members nodePtr tail; }; #define QUEUE_H #endif // Class declaration file: Queue.h // Linked List implementation of queue ADT. #ifndef QUEUE_H #include "LinkedList.h" class queue: protected LinkedList { public: // Class constructors queue(); queue(const queue &q); // Member functions bool isEmpty(); void enqueue(const elementType &item); elementType dequeue(); protected: // Data members nodePtr tail; }; #define QUEUE_H #endif // Class implementation file: Queue.cpp // Linked List implementation of the queue ADT. #include "Queue.h" #include // Default constructor: Makes an empty queue // queue:: queue(): LinkedList() { tail = NULL; } // Class implementation file: Queue.cpp // Linked List implementation of the queue ADT. #include "Queue.h" #include // Default constructor: Makes an empty queue // queue:: queue(): LinkedList() { tail = NULL; } Let’s assume that the getNode and head members in LinkedList were declared protected, not private! Let’s also assume that the elementType typedef occurred in the LinkedList definition! Let’s assume that the getNode and head members in LinkedList were declared protected, not private! Let’s also assume that the elementType typedef occurred in the LinkedList definition! The queue class “inherits” from the LinkedList class, so all LinkedList members are accessible to any queue. With its “protected” access specifier, the public and protected members of LinkedList are considered protected in the queue class. The queue class “inherits” from the LinkedList class, so all LinkedList members are accessible to any queue. With its “protected” access specifier, the public and protected members of LinkedList are considered protected in the queue class.

CS // Copy constructor: Makes a deep // // copy of the *this queue. // queue:: queue(const queue &q) { nodePtr copyPreviousPtr, copyPtr, origPtr; if (q.head == NULL) tail = head = NULL; else { head = getNode(q.head->item); copyPreviousPtr = head; origPtr = q.head->next; while (origPtr != NULL) { copyPtr = getNode(origPtr->item); copyPreviousPtr->next = copyPtr; copyPreviousPtr = copyPtr; origPtr = origPtr->next; } tail = copyPreviousPtr; } // isEmpty function; Determines // // if the *this queue is empty. // bool queue:: isEmpty() { return (head == NULL); } // Copy constructor: Makes a deep // // copy of the *this queue. // queue:: queue(const queue &q) { nodePtr copyPreviousPtr, copyPtr, origPtr; if (q.head == NULL) tail = head = NULL; else { head = getNode(q.head->item); copyPreviousPtr = head; origPtr = q.head->next; while (origPtr != NULL) { copyPtr = getNode(origPtr->item); copyPreviousPtr->next = copyPtr; copyPreviousPtr = copyPtr; origPtr = origPtr->next; } tail = copyPreviousPtr; } // isEmpty function; Determines // // if the *this queue is empty. // bool queue:: isEmpty() { return (head == NULL); } // Enqueue function; Inserts item // // into the back of the *this queue. // void queue:: enqueue(const elementType &elt) { nodePtr newPtr = getNode(elt); assert (newPtr != NULL); if (head == NULL) head = tail = newPtr; else { tail->next = newPtr; tail = newPtr; } // Dequeue function; Removes item // // from the front of the *this queue // // (assuming such an item exists). // elementType queue:: dequeue() { elementType elt; nodePtr oldHead; assert(head != NULL); oldHead = head; elt = head->item; head = head->next; if (head == NULL) tail = NULL; delete oldHead; return elt; } // Enqueue function; Inserts item // // into the back of the *this queue. // void queue:: enqueue(const elementType &elt) { nodePtr newPtr = getNode(elt); assert (newPtr != NULL); if (head == NULL) head = tail = newPtr; else { tail->next = newPtr; tail = newPtr; } // Dequeue function; Removes item // // from the front of the *this queue // // (assuming such an item exists). // elementType queue:: dequeue() { elementType elt; nodePtr oldHead; assert(head != NULL); oldHead = head; elt = head->item; head = head->next; if (head == NULL) tail = NULL; delete oldHead; return elt; }

CS // Program file: carwash.cpp // // This program simulates the operation of a // // car wash over 10 hours (600 minutes) of // // operation. The variables timeForWash and // // probOfArrival represent the time it takes // // to run one car through the car wash and // // the probability that a car arrives in any // // given minute. // #include #include "Queue.h" using namespace std; float random(); void initializeRandomSeed(); // The main function simulates the arrival of // // 600 cars at the car wash, queueing those // // which have to wait, and keeping a running // // tally of how long the cars are queued up. // void main() { int timeForWash, minute, timeEnteredQueue, carsWashed, totalQueueMin, timeLeftOnCar; float probOfArrival; queue carQueue; // Program file: carwash.cpp // // This program simulates the operation of a // // car wash over 10 hours (600 minutes) of // // operation. The variables timeForWash and // // probOfArrival represent the time it takes // // to run one car through the car wash and // // the probability that a car arrives in any // // given minute. // #include #include "Queue.h" using namespace std; float random(); void initializeRandomSeed(); // The main function simulates the arrival of // // 600 cars at the car wash, queueing those // // which have to wait, and keeping a running // // tally of how long the cars are queued up. // void main() { int timeForWash, minute, timeEnteredQueue, carsWashed, totalQueueMin, timeLeftOnCar; float probOfArrival; queue carQueue; Example Queue Application cout << "Enter time (in minutes)" << " to wash one car: "; cin >> timeForWash; cout << "Enter probability of " << "arrival in any minute: "; cin >> probOfArrival; carsWashed = 0; totalQueueMin = 0; timeLeftOnCar = 0; for (minute = 1; minute <= 600; minute++) { if (random() < probOfArrival) carQueue.enqueue(minute); if ((timeLeftOnCar == 0) && !carQueue.isEmpty()) { timeEnteredQueue = carQueue.dequeue(); totalQueueMin += (minute – timeEnteredQueue); carsWashed++; timeLeftOnCar = timeForWash; } if (timeLeftOnCar != 0) timeLeftOnCar--; } cout << "Enter time (in minutes)" << " to wash one car: "; cin >> timeForWash; cout << "Enter probability of " << "arrival in any minute: "; cin >> probOfArrival; carsWashed = 0; totalQueueMin = 0; timeLeftOnCar = 0; for (minute = 1; minute <= 600; minute++) { if (random() < probOfArrival) carQueue.enqueue(minute); if ((timeLeftOnCar == 0) && !carQueue.isEmpty()) { timeEnteredQueue = carQueue.dequeue(); totalQueueMin += (minute – timeEnteredQueue); carsWashed++; timeLeftOnCar = timeForWash; } if (timeLeftOnCar != 0) timeLeftOnCar--; }

CS cout << endl << carsWashed << " cars were washed" << endl; cout.setf(ios::fixed); cout << setprecision(2); cout << "Average wait in queue: " << float(totalQueueMin)/carsWashed << " minutes." << endl << endl; } // Function random produces random floating-point number between 0 and 1. // float random() { // Generate random number seed the first time the function is called. static int iteration = 0; iteration++; if (iteration == 1) initializeRandomSeed(); return (float(rand()) / RAND_MAX); } // Function initializeRandomSeed uses the ctime library function // // time() to seed the rand() function via the srand() function. // void initializeRandomSeed() { // Time-elapsed value, used to seed the random number generator. time_t randomNumberSeed; time(&randomNumberSeed); srand(int(randomNumberSeed)); return; } cout << endl << carsWashed << " cars were washed" << endl; cout.setf(ios::fixed); cout << setprecision(2); cout << "Average wait in queue: " << float(totalQueueMin)/carsWashed << " minutes." << endl << endl; } // Function random produces random floating-point number between 0 and 1. // float random() { // Generate random number seed the first time the function is called. static int iteration = 0; iteration++; if (iteration == 1) initializeRandomSeed(); return (float(rand()) / RAND_MAX); } // Function initializeRandomSeed uses the ctime library function // // time() to seed the rand() function via the srand() function. // void initializeRandomSeed() { // Time-elapsed value, used to seed the random number generator. time_t randomNumberSeed; time(&randomNumberSeed); srand(int(randomNumberSeed)); return; }