25
Queues Queues

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

Embed Size (px)

Citation preview

Page 1: 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

QueuesQueues

Page 2: 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

Queue DefinitionQueue Definition

Ordered list with property:Ordered list with property: All insertions take place at one end (tail)All insertions take place at one end (tail) All deletions take place at other end (head)All deletions take place at other end (head)

Queue: Q = (aQueue: Q = (a00, a, a11, …, a, …, an-1n-1))

a0 is the front element, aa0 is the front element, an-1n-1 is the tail, is the tail, and aand aii is behind a is behind ai-1i-1 for all i, 1 <= i < n for all i, 1 <= i < n

Page 3: 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

Queue DefinitionQueue Definition

Because of insertion and deletion Because of insertion and deletion properties,properties,

Queue is very similar to:Queue is very similar to:

Line at the grocery storeLine at the grocery store

Cars in trafficCars in traffic

Network packetsNetwork packets

……..

Also called Also called first-in first outfirst-in first out lists lists

Page 4: 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

Queue Implementation Queue Implementation IdeasIdeas

Container type class for holding data Container type class for holding data Array versus Linked List? Who’s Array versus Linked List? Who’s

better?better?Head index pointerHead index pointer

Position right before first element in Position right before first element in queuequeueTail index pointerTail index pointer

Position of last element in queuePosition of last element in queue

Page 5: 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

Array-Based Queue Array-Based Queue DefinitionDefinition

template <class KeyType>template <class KeyType>class Queueclass Queue{{

public:public:Queue(int MaxQueueSize = DefaultSize);Queue(int MaxQueueSize = DefaultSize);~Queue();~Queue();

bool IsFull();bool IsFull();bool IsEmpty();bool IsEmpty();void Add(const KeyType& item);void Add(const KeyType& item);KeyType* Delete(KeyType& item);KeyType* Delete(KeyType& item);

private:private:void QueueFull(); void QueueFull(); // error handling// error handlingvoid QueueEmpty();void QueueEmpty(); // error handling// error handlingint head, tail;int head, tail;KeyType* queue;KeyType* queue;int MaxSize;int MaxSize;

};};

Page 6: 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

Queue ImplementationQueue Implementation

Constructor:Constructor:template <class KeyType>template <class KeyType>

Queue<KeyType>::Queue(int MaxQueueSize): Queue<KeyType>::Queue(int MaxQueueSize): MaxSize(MaxQueueSize)MaxSize(MaxQueueSize)

{{

queue = new KeyType[MaxSize];queue = new KeyType[MaxSize];

head = tail = -1;head = tail = -1;

}}

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

Queue ImplementationQueue Implementation

Destructor:Destructor:template <class KeyType>template <class KeyType>

Queue<KeyType>::~Queue()Queue<KeyType>::~Queue()

{{

delete [] queue;delete [] queue;

head = tail = -1;head = tail = -1;

}}

Page 8: 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

Queue ImplementationQueue Implementation

IsFull() and IsEmpty():IsFull() and IsEmpty():

template <class KeyType>template <class KeyType>bool Queue<KeyType>::IsFull()bool Queue<KeyType>::IsFull()

{{return (tail == (MaxSize-1));return (tail == (MaxSize-1));

}}

template <class KeyType>template <class KeyType>bool Queue<KeyType>::IsEmpty()bool Queue<KeyType>::IsEmpty()

{{return (head == tail);return (head == tail);

}}

Page 9: 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

Queue ImplementationQueue Implementation

Add() and Delete():Add() and Delete():template <class KeyType>template <class KeyType>void Queue<KeyType>::Add (const KeyType& item)void Queue<KeyType>::Add (const KeyType& item)

{{if (IsFull()) {QueueFull(); return;}if (IsFull()) {QueueFull(); return;}else { tail = tail + 1; queue[tail] = item; }else { tail = tail + 1; queue[tail] = item; }

}}

template <class KeyType>template <class KeyType>KeyType* Queue<KeyType>::Delete(KeyType& item)KeyType* Queue<KeyType>::Delete(KeyType& item)

{{

if (IsEmpty()) {QueueEmpty(); return 0};if (IsEmpty()) {QueueEmpty(); return 0};else { head = head + 1; item = queue[head]; return else { head = head + 1; item = queue[head]; return

&item; }&item; }}}

Page 10: 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

Example: Job SchedulingExample: Job Scheduling

OS has to manage how jobs (programs) OS has to manage how jobs (programs) are executed on the processor – 2 are executed on the processor – 2 typical techniques:typical techniques:-Priority based: Some ordering over of -Priority based: Some ordering over of jobs based on importance jobs based on importance

(Professor X’s jobs should be (Professor X’s jobs should be allowed to run allowed to run first over Professor first over Professor Y).Y).-Queue based: Equal priority, -Queue based: Equal priority, schedule in first in first out order.schedule in first in first out order.

Page 11: 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

Queue Based Job Queue Based Job ProcessingProcessing

FronFrontt

RearRear Q[0] Q[1] Q[2] Q[0] Q[1] Q[2] Q[3]Q[3]

CommenCommentsts

-1-1 -1-1 InitialInitial

-1-1 00 J1J1 Job 1 Job 1 EntersEnters

-1-1 11 J1 J2J1 J2 Job 2 Job 2 EntersEnters

-1-1 22 J1 J2 J3J1 J2 J3 Job 3 Job 3 EntersEnters

00 22 J2 J3J2 J3 Job 1 Job 1 LeavesLeaves

00 33 J2 J3 J2 J3 J4 J4

Job 4 Job 4 EntersEnters

11 33 J3 J3 J4 J4

Job 2 Job 2 LeavesLeaves

MaxSize = 4

Page 12: 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

Job ProcessingJob Processing When J4 enters the queue, rear is updated to 3.When J4 enters the queue, rear is updated to 3. When rear is 3 in a 4-entry queue, run out of space.When rear is 3 in a 4-entry queue, run out of space. The array may not really be full though, if head is The array may not really be full though, if head is

not not

-1.-1. Head can be > -1 if items have been removed from Head can be > -1 if items have been removed from

queue.queue.

Possible Solution: When rear = (maxSize – 1) attempt Possible Solution: When rear = (maxSize – 1) attempt to shift data forwards into empty spaces and then to shift data forwards into empty spaces and then do Add.do Add.

Page 13: 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

Queue Shift Queue Shift

private void shiftQueue(KeyType* queue, int & private void shiftQueue(KeyType* queue, int & head, int & tail)head, int & tail)

{{int difference = head – (-1); int difference = head – (-1); // head + 1// head + 1for (int j = head + 1; j < maxSize; j++)for (int j = head + 1; j < maxSize; j++){{

queue[j-difference] = queue[j];queue[j-difference] = queue[j];}}head = -1;head = -1;tail = tail – difference;tail = tail – difference;

}}

Page 14: 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

Queue ShiftQueue Shift

Worst Case For Queue Shift:Worst Case For Queue Shift:

Full QueueFull Queue

Alternating Delete and Add statementsAlternating Delete and Add statements

FronFrontt

RearRear Q[0] Q[1] Q[2] Q[0] Q[1] Q[2] Q[3]Q[3]

CommenCommentsts

-1-1 33 J1 J2 J3 J1 J2 J3 J4J4

InitialInitial

00 33 J2 J3 J2 J3 J4J4

Job 1 Job 1 LeavesLeaves

-1-1 33 J2 J3 J4 J2 J3 J4 J5J5

Job 5 Job 5 EntersEnters

00 33 J3 J4 J3 J4 J5J5

Job 2 Job 2 EntersEnters

-1-1 33 J3 J4 J5 J3 J4 J5 J6J6

Job 6 Job 6 LeavesLeaves

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

Worst Case Queue ShiftWorst Case Queue Shift

Worst Case:Worst Case: Shift entire queue: Cost of Shift entire queue: Cost of O(n)O(n) Do every time perform an addDo every time perform an add Too expensive to be usefulToo expensive to be useful

Worst case is not that unlikely, so this Worst case is not that unlikely, so this suggests finding an alternative suggests finding an alternative implementation.implementation.

Page 16: 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

Circular Array Circular Array ImplementationImplementation

Basic Idea: Allow the queue to wrap-Basic Idea: Allow the queue to wrap-aroundaround

Implement with addition mod size: Implement with addition mod size: tail = (tail + 1) % queueSize;tail = (tail + 1) % queueSize;

01

2

3

4

N-1

N-2J1

J2

J3

J4

01

2

3

4

N-1

N-2J2J3J1

Page 17: 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

Linked QueuesLinked Queues Problems with implementing queues on Problems with implementing queues on

top of arraystop of arrays Sizing problems (bounds, clumsy resizing, …)Sizing problems (bounds, clumsy resizing, …) Non-circular Array – Data movement problemNon-circular Array – Data movement problem

Now that have the concepts of list nodes, Now that have the concepts of list nodes, can take advantage of to represent can take advantage of to represent queues.queues.

Need to determine appropriate way of:Need to determine appropriate way of: Representing front and rearRepresenting front and rear Facilitating node addition and deletion at the Facilitating node addition and deletion at the

ends.ends.

Page 18: 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

Linked QueuesLinked Queues

CAT

Front Rear

MATHAT

Front Rear Rear

Add(Hat) Add(Mat) Add(Cat) Delete()

Page 19: 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

Linked QueuesLinked Queues

Class QueueNode{Class QueueNode{

friend class Queue;friend class Queue;

public:public:

QueueNode(int d, QueueNode * l); QueueNode(int d, QueueNode * l);

private:private:

int data;int data;

QueueNode *link;QueueNode *link;

};};

Page 20: 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

Linked QueuesLinked Queuesclass Queueclass Queue{{

public:public:Queue();Queue();~Queue();~Queue();void Add(const int);void Add(const int);int* Delete(int&);int* Delete(int&);bool isEmpty();bool isEmpty();

private:private:QueueNode* front;QueueNode* front;QueueNode* rear;QueueNode* rear;void QueueEmpty();void QueueEmpty();

}}

Page 21: 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

Linked QueuesLinked Queues

Queue::Queue()Queue::Queue()

{{

front = 0;front = 0;

rear = 0;rear = 0;

}}

bool Queue::isEmpty()bool Queue::isEmpty()

{{

return (front == 0);return (front == 0);

}}

Front Rear

0 0

Page 22: 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

Linked QueuesLinked Queuesvoid Queue::Add(const int y)void Queue::Add(const int y)

{{

// Create a new node that contains data y// Create a new node that contains data y

// Has to go at end// Has to go at end

// Set current rear link to new node pointer// Set current rear link to new node pointer

// Set new rear pointer to new node pointer// Set new rear pointer to new node pointer

rear = rear->link = new QueueNode(y, 0);rear = rear->link = new QueueNode(y, 0);

}}

CAT

Front

MATHAT

Rear Rear

Page 23: 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

Linked QueuesLinked Queuesint * Queue::Delete(int & retValue)int * Queue::Delete(int & retValue){{

// handle empty case// handle empty caseif (isEmpty()) { QueueEmpty(); return 0;}if (isEmpty()) { QueueEmpty(); return 0;}QueueNode* toDelete = front;QueueNode* toDelete = front;retValue = toDelete.data;retValue = toDelete.data;front = toDelete->link;front = toDelete->link;delete toDelete;delete toDelete;return &retValue;return &retValue;

}}

CAT

Front

MATHAT

ReartoDelete

HAT

returnValue

Front

Page 24: 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

Queue DestructorQueue DestructorQueue destructor needs to remove all Queue destructor needs to remove all

nodes from head to tail.nodes from head to tail.

CAT

Front

MATHAT

RearFront FrontTemp Temp

0 0if (front) {QueueNode* temp;while (front != rear) {

temp = front;front = front -> link;delete temp; }

delete front;front = rear = 0; }

Page 25: 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

Front vs DeleteFront vs Delete

Implementation as written has to Implementation as written has to remove the item from the queue to remove the item from the queue to read data value. read data value.

Some implementations provide two Some implementations provide two separate functions:separate functions: Front() which returns the data in the first Front() which returns the data in the first

elementelement Delete() which removes the first element Delete() which removes the first element

from the queue, without returning a value.from the queue, without returning a value.