Queue Section 3 6/12/20161. The Abstract Data Type Queue A queue is a list from which items are deleted from one end (front) and into which items are.

Slides:



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

What is a Queue? A queue is a FIFO “first in, first out” structure.
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
Fundamentals of Python: From First Programs Through Data Structures
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Data Structure Dr. Mohamed Khafagy.
Queue Overview Queue ADT Basic operations of queue
CS Data Structures II Review COSC 2006 April 14, 2017
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.
Queues and Priority Queues
Chapter 13 Queues and Priority Queues CS Data Structures Mehmet H Gunes Modified from authors’ slides.
© 2006 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 Queues CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
Cmpt-225 Queues. A queue is a data structure that only allows items to be inserted at the end and removed from the front Queues are FIFO (First In First.
Stacks and Queues. Sample PMT online… Browse 1120/sumII05/PMT/2004_1/
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.
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.
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.
Queues and Priority Queues
© 2006 Pearson Addison-Wesley. All rights reserved8 A-1 Chapter 8 Queues (slightly modified by Dan Fleck)
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2b. Simple Containers: The Queue.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
Data Structures Using C++ 2E Chapter 8 Queues. Data Structures Using C++ 2E2 Objectives Learn about queues Examine various queue operations Learn how.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 3)
© 2006 Pearson Addison-Wesley. All rights reserved8 A-1 Chapter 8 Queues.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Queues. Queue Definition Ordered list with property: All insertions take place at one end (tail) All insertions take place at one end (tail) All deletions.
1 Stacks and Queues Based on D.S. Malik, Java Programming: Program Design Including Data Structures.
Data Structures Using Java1 Chapter 7 Queues. Data Structures Using Java2 Chapter Objectives Learn about queues Examine various queue operations Learn.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 7: Queues Data Abstraction & Problem Solving with C++
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 6: Stacks Data Abstraction & Problem Solving with C++
Chapter 8 Queue I CS Data Structures I COSC2006 April 24, 2017
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
EC-211 DATA STRUCTURES LECTURE 9. Queue Data Structure An ordered group of homogeneous items or elements. Queues have two ends: – Elements are added at.
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)
Computer Science Department Data Structures and Algorithms Queues Lecture 5.
Chapter 8 Queues. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
CS Data Structures I Chapter 7 Queue I. 2 Topics Introduction Queue Application Implementation Linked List Array ADT List.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 7: Queues Data Abstraction & Problem Solving with C++
© 2011 Pearson Addison-Wesley. All rights reserved 8 B-1 Chapter 8 (continued) Queues.
Chapter 7 Queues Introduction Queue applications Implementations.
11/07/141 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.
Queues Lecture 4. Lecture Objectives  Learn about queues  Examine various queue operations  Learn how to implement a queue as an array  Learn how.
Chapter 7 A Queues. © 2004 Pearson Addison-Wesley. All rights reserved7 A-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 7: Queues Data Abstraction & Problem Solving with C++
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.
Queues Chapter 8 (continued)
CSCE 210 Data Structures and Algorithms
Chapter 7 Queues.
Data Abstraction & Problem Solving with C++
CS505 Data Structures and Algorithms
CC 215 Data Structures Queue ADT
Csc 2720 Data structure Instructor: Zhuojun Duan
CENG 213 Data Structure Queue 7/2/2018.
Stacks and Queues.
The Abstract Data Type Queue
Chapter 4 Linked Lists
CMSC 341 Lecture 5 Stacks, Queues
Queues.
Queues.
Chapter 4 Linked Lists.
CSC 143 Queues [Chapter 7].
Chapter 4 Linked Lists.
Figure 7.1 Some queue operations. Figure 7.1 Some queue operations.
Chapter 8 Queues © 2006 Pearson Addison-Wesley. All rights reserved.
Queues cont. Chapter 8 © 2011 Pearson Addison-Wesley. All rights reserved.
CSCS-200 Data Structure and Algorithms
Queues Chapter 8 © 2011 Pearson Addison-Wesley. All rights reserved.
Queues.
Presentation transcript:

Queue Section 3 6/12/20161

The Abstract Data Type Queue A queue is a list from which items are deleted from one end (front) and into which items are inserted at the other end (rear, or back) It is like line of people waiting to purchase tickets: Queue is referred to as a first-in-first-out (FIFO) data structure. The first item inserted into a queue is the first item to leave Queues have many applications in computer systems: Any application where a group of items is waiting to use a shared resource will use a queue. e.g. jobs in a single processor computer print spooling information packets in computer networks. A simulation: a study to see how to reduce the waiting time involved in an application 6/12/20162

A Queue 6/12/20163 front rear dequeue enqueue

ADT Queue Operations createQueue() Create an empty queue destroyQueue() Destroy a queue isEmpty():boolean Determine whether a queue is empty enqueue(in newItem:QueueItemType) throw QueueException Inserts a new item at the end of the queue (at the rear of the queue) dequeue() throw QueueException dequeue(out queueFront:QueueItemType) throw QueueException Removes (and returns) the element at the front of the queue Remove the item that was added earliest getFront(out queueFront:QueueItemType) throw QueueException Retrieve the item that was added earliest (without removing) 6/12/20164

Some Queue Operations OperationQueue after operation x.createQueue()an empty queue front  x.enqueue(5)5 x.enqueue(3)5 3 x.enqueue(2)5 3 2 x.dequeue()3 2 x.enqueue(7)3 2 7 x.dequeue(a)2 7 (a is 3) x.getFront(b)2 7 (b is 2) 6/12/20165

An Application -- 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 6/12/20166

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 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 6/12/20167

Recognizing Palindromes (cont.) 6/12/20168 The results of inserting a string into both a queue and a stack

Recognizing Palindromes -- Algorithm isPal(in str:string) : boolean // Determines whether str is a palindrome or not aQueue.createQueue(); aStack.createStack(); len = length of str; for (i=1 through len) { nextChar = ith character of str; aQueue.enqueue(nextChar); aStack.push(nextChar); } charactersAreEqual = true; while (aQueue is not empty and charactersAreEqual) { aQueue.getFront(queueFront); aStack.getTop(stackTop); if (queueFront equals to stackTop) { aQueue.dequeue(); aStack.pop()}; } else chractersAreEqual = false; } return charactersAreEqual; 6/12/20169

Implementations of the ADT Queue Pointer-based implementations of 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 A reference to the back Array-based implementations of queue A naive array-based implementation of queue A circular array-based implementation of queue 6/12/201610

Pointer-based implementations of queue 6/12/ a linear linked list with two external pointers a circular linear linked list with one external pointer

A Pointer-Based Implementation -- enqueue 6/12/ Inserting an item into a nonempty queue Inserting an item into an empty queue a) before insertionb) after insertion

A Pointer-Based Implementation -- dequeue 6/12/ Deleting an item from a queue of more than one item Deleting an item from a queue with one item after deletion tempPtr = frontPtr; frontPtr = NULL; backPtr = NULL; delete tempPtr; before deletion tempPtr

A Pointer-Based Implementation – Header File #include "QueueException.h" typedef desired-type-of-queue-item QueueItemType; class Queue { public: Queue(); // default constructor Queue(const Queue& Q); // copy constructor ~Queue(); // destructor bool isEmpty() const;// Determines whether the queue is empty. void enqueue(QueueItemType newItem); // Inserts an item at the back of a queue. void dequeue() throw(QueueException); // Dequeues the front of a queue. // Retrieves and deletes the front of a queue. void dequeue(QueueItemType& queueFront) throw(QueueException); // Retrieves the item at the front of a queue. void getFront(QueueItemType& queueFront) const throw(QueueException); 6/12/201614

A Pointer-Based Implementation – Header File 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; }; // end struct QueueNode *backPtr; QueueNode *frontPtr; } 6/12/201615

A Pointer-Based Implementation – constructor, deconstructor, isEmpty #include "QueueP.h" // header file Queue::Queue() : backPtr(NULL), frontPtr(NULL){} // default constructor Queue::~Queue() {// destructor while (!isEmpty()) dequeue(); // backPtr and frontPtr are NULL at this point } bool Queue::isEmpty() const{ // isEmpty return backPtr == NULL; } 6/12/201616

A Pointer-Based Implementation – enqueue void Queue::enqueue(QueueItemType newItem) {// enqueue // 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 } 6/12/201617

A Pointer-Based Implementation – dequeue void Queue::dequeue() throw(QueueException) { if (isEmpty()) throw QueueException("QueueException: empty queue, cannot dequeue"); else { // queue is not empty; remove front QueueNode *tempPtr = frontPtr; if (frontPtr == backPtr) { // one node in queue frontPtr = NULL; backPtr = NULL; } else frontPtr = frontPtr->next; tempPtr->next = NULL; // defensive strategy delete tempPtr; }} 6/12/201618

A Pointer-Based Implementation – dequeue, getFront void Queue::dequeue(QueueItemType& queueFront) throw(QueueException) { if (isEmpty()) throw QueueException("QueueException: empty queue, cannot dequeue"); else { // queue is not empty; retrieve front queueFront = frontPtr->item; dequeue(); // delete front }} void Queue::getFront(QueueItemType& queueFront) const throw(QueueException) { if (isEmpty()) throw QueueException("QueueException: empty queue, cannot getFront"); else // queue is not empty; retrieve front queueFront = frontPtr->item; } 6/12/201619

A circular linked list with one external pointer 6/12/ Queue Operations constructor ? isEmpty ? enqueue ? dequeue ? getFront ?

A Naive Array-Based Implementation of Queue 6/12/ Rightward drift can cause the queue to appear full even though the queue contains few entries. We may shift the elements to left in order to compensate for rightward drift, but shifting is expensive Solution: A circular array eliminates rightward drift.

A Circular Array-Based Implementation 6/12/ When either front or back advances past MAX_QUEUE-1 it wraps around to 0.

The effect of some operations of the queue 6/12/ Initialize: front=0; back=MAX_QUEUE-1; Insertion : back = (back+1) % MAX_QUEUE; items[back] = newItem; Deletion : front = (front+1) % MAX_QUEUE; NOT ENOUGH

PROBLEM – Queue is Empty or Full 6/12/ front and back cannot be used to distinguish between queue-full and queue-empty conditions. ? Empty (back+1)%MAX_QUEUE == front ? Full (back+1)%MAX_QUEUE == front So, we need extra mechanism to distinguish between queue-full and queue-empty conditions.

Solutions for Queue-Empty/Queue-Full Problem 1. Using a counter to keep the number items in the queue. Initialize count to 0 during creation; Increment count by 1 during insertion; Decrement count by 1 during deletion. count=0  empty; count=MAX_QUEUE  full 2. Using isFull flag to distinguish between the full and empty conditions. When the queue becomes full, set isFullFlag to true; When the queue is not full set isFull flag to false; 3. Using an extra array location (and leaving at least one empty location in the queue). ( MORE EFFICIENT ) Declare MAX_QUEUE+1 locations for the array items, but only use MAX_QUEUE of them. We do not use one of the array locations. Full: front equals to (back+1)%(MAX_QUEUE+1) Empty: front equals to back 6/12/201625

Using a counter To initialize the queue, set front to 0 back to MAX_QUEUE–1 count to 0 Inserting into a queue back = (back+1) % MAX_QUEUE; items[back] = newItem; ++count; Deleting from a queue front = (front+1) % MAX_QUEUE; --count ; Full: count == MAX_QUEUE Empty: count == 0 6/12/201626

Array-Based Implementation Using a counter – Header File #include "QueueException.h" const int MAX_QUEUE = maximum-size-of-queue; typedef desired-type-of-queue-item QueueItemType; class Queue { public: Queue(); // default constructor 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; }; 6/12/201627

Array-Based Implementation Using a counter – constructor, isEmpty, enqueue Queue::Queue():front(0), back(MAX_QUEUE-1), count(0) {} bool Queue::isEmpty() const { return count == 0); } void Queue::enqueue(QueueItemType newItem) throw(QueueException) { if (count == MAX_QUEUE) throw QueueException("QueueException: queue full on enqueue"); else { // queue is not full; insert item back = (back+1) % MAX_QUEUE; items[back] = newItem; ++count; } 6/12/201628

Array-Based Implementation Using a counter –dequeue void Queue::dequeue() throw(QueueException) { if (isEmpty()) throw QueueException("QueueException: empty queue, cannot dequeue"); else { // queue is not empty; remove front front = (front+1) % MAX_QUEUE; --count; }} void Queue::dequeue(QueueItemType& queueFront) throw(QueueException) { if (isEmpty()) throw QueueException("QueueException: empty queue, cannot dequeue"); else { // queue is not empty; retrieve and remove front queueFront = items[front]; front = (front+1) % MAX_QUEUE; --count; }} 6/12/201629

Array-Based Implementation Using a counter –dequeue void Queue::getFront(QueueItemType& queueFront) const throw(QueueException) { if (isEmpty()) throw QueueException("QueueException: empty queue, cannot getFront"); else // queue is not empty; retrieve front queueFront = items[front]; } 6/12/201630

Using isFull flag To initialize the queue, set front = 0; back = MAX_QUEUE–1; isFull = false; Inserting into a queue back = (back+1) % MAX_QUEUE; items[back] = newItem; if ( (back+1)%MAX_QUEUE == front)) isFull = true; Deleting from a queue front = (front+1) % MAX_QUEUE; isFull = false; Full: isFull == true Empty: isFull==false && ((back+1)%MAX_QUEUE == front)) 6/12/201631

Using an extra array location To initialize the queue, allocate (MAX_QUEUE+1) locations front=0; back=0; front holds the index of the location before the front of the queue. Inserting into a queue (if queue is not full) back = (back+1) % (MAX_QUEUE+1); items[back] = newItem; Deleting from a queue (if queue is not empty) front = (front+1) % (MAX_QUEUE+1); Full: (back+1)%(MAX_QUEUE+1) == front Empty: front == back 6/12/ full queue empty queue

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) 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) Simple to implement, but inefficient. 6/12/201633

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 Pointer-based implementations A linked list implementation More efficient; no size limit The ADT list implementation Simpler to write; inefficient 6/12/201634

A Summary of Position-Oriented ADTs Position-oriented ADTs: List, Stack, Queue Stacks and Queues Only the end positions can be accessed Lists All positions can be accessed 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 ADT list operations generalize stack and queue operations getLength, insert, remove, retrieve 6/12/201635

Application: Simulation 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 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 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 6/12/201636

Application: Simulation 6/12/201637

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 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 6/12/201638

A typical instance of the event list 6/12/201639

A partial trace of the bank simulation algorithm 6/12/ Data (Customer Arrivals) :

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 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 6/12/201641