8
QUEUES Linear Data Structures Are collections of items arranged in a straight line (i.e. in array, or maybe. . .linked list!) Stacks and Queues are linear data structures, where data can be stored linearly! However: o Some rules are applied when adding and removing items from Stacks and Queues. Queues Defn: As a data structure, a queue is an ordered collection of data items with the property that items can be removed only at one end, called the front of the queue, and items can be added only at the other end, called the back of the queue. Front : Remove ONLY Back : Add ONLY A Queue is a container where the first item inserted must comes out first. (a waiting line) So it is a “First – in – First – Out” FIFO or First-Come- First-Served (FCFS) structure. Basic operations are: construct: Create an empty queue empty: Check if a queue is empty addQ: Add a value at the back of the queue front: Retrieve the value at the front of the queue removeQ: Remove the value at the front of the queue Examples a) A long, narrow, open-ends, Cars Park: B CA Car A must have entered first, then B, and last C! First one in is A, must be the first to come out. C is the last to come out, since the Last one in. b) I/O buffers: queues, scrolls, deques From a file: (queue) 1

Queues

Embed Size (px)

DESCRIPTION

Read is enjoyable

Citation preview

Page 1: Queues

QUEUESLinear Data Structures

Are collections of items arranged in a straight line (i.e. in array, or maybe. . .linked list!) Stacks and Queues are linear data structures, where data can be stored linearly! However:

o Some rules are applied when adding and removing items from Stacks and Queues.

Queues Defn: As a data structure, a queue is an ordered collection of data items with the property

that items can be removed only at one end, called the front of the queue, and items can be added only at the other end, called the back of the queue.

Front: Remove ONLYBack: Add ONLY

A Queue is a container where the first item inserted must comes out first. (a waiting line) So it is a “First – in – First – Out” FIFO or First-Come-First-Served (FCFS) structure.

Basic operations are: construct: Create an empty queue empty: Check if a queue is empty addQ: Add a value at the back of the queue front: Retrieve the value at the front of the queue removeQ: Remove the value at the front of the queue

Examples a) A long, narrow, open-ends, Cars Park: B CA Car A must have entered first, then B, and last C! First one in is A, must be the first to come out. C is the last to come out, since the Last one in.

b) I/O buffers: queues, scrolls, deques From a file: (queue)

i) Interactively: (scroll — queue on one end, stack on the other

1

Infile >> X;

X

Input Buffer

CPU

MemoryDisk

Input Buffer queues input for the CPU

Page 2: Queues

ii) Screen handling: (deque — double-ended queue)

c) Scheduling queues in a multi-user computer system

Printer queue: When files are submitted to a printer, they are placed in the printer queue. The printer software executes an algorithm something like:

for (;;) { while (printerQueue.empty()) sleep 1; printFile = printerQueue.removeQ(); Print(printFile);}

Other Queues:1. Resident queue: On disk, waiting for memory2. Ready queue: In memory — has everything it needs to run,

except the CPU3. Suspended queue: Waiting for I/O transfer or to be reassigned the CPU

2

Scroll:Front: Remove

or Add

Back: Add orRemove

Page 3: Queues

d) CPU Scheduling: Probably uses a priority queue: Items with lower priority are behind all those with higher

priority. (Usually a new item is inserted behind those with the same priority.)

Queue: Array-Based Representation Now, we need to define a Data Structure of the Queue. Then, we need to write the operations insert, remove, empty, and init.

#define MAX 10; // MAX is a constant equal to 10 Typedef char itemType; // another name for char !

typedef struct{ // A Queue to hold 10 Characters int Front, Rear, Count; // Why 3 variables ? itemType items[MAX]; // array of 10 characters } Queue; // The new type is called Queue

itemsFront Rear Count Queue (a new type -a structure )

Problem: If we keep inserting items at Rear, and remove items from Front, then we will need a

mechanism for shifting items every time a new item is added Additions to the queue would result in incrementing myBack. Deletions from the queue would result in incrementing myFront. Clearly, we’d run out of space soon! Solutions include:

3

12

3

Page 4: Queues

o Shifting the elements downward with each deletion o Viewing array as a circular buffer, i.e. wrapping the end to the front

“Circular” Array-Implementation Wraparound keeps the addition/deletion cycle from walking off the edge of the storage array. Say, myArray has QUEUE_CAPACITY elements. When myBack hits the end of myArray, a deletion should wrap myBack around to the first

element of myArray, viz:o myBack++;

if (myBack = = QUEUE_CAPACITY)o myBack = 0;

//equivalently (preferred, concise)o myBack = (myBack + 1) % QUEUE_CAPACITY;

Queues: Operations We need now to write functions insert(), remove() init(), and empty(), so we can access the

Queue ONLY via these operations ! Let’s start with init()

void init( Queue *Q) // Used to initialize the queue { Q->Font = 0; // index of first item in the array Q->Rear = 0; // index of last item Q->Count = 0; // number of items in the array of the queue }

And empty(): int empty( Queue *Q) // return true if Queue is empty { return (Q->Count == 0); // Zero items in Queue }

Now the insert() method: void insert( Queue *Q, itemType R) // R is the item to add { if(Q->Count != MAX) { // Check if Max is reached ! printf(“Error: Queue is Full.”); exit(1); } else { // Now we need to add R at the Rear of the queue // i.e. in the array items at location hold by Rear Q->items[ Q->Rear ] = R; // increment Rear by 1, if MAX is reach switch to Zero !! Q->Rear = (Q->Rear + 1) % MAX; ++(Q->Count); // and Finally increment Count } }

And the Remove() method: itemType remove( Queue *Q) // remove the first item inserted { // and return it the calling function if(Q->Count != 0) { // if no items exist, nothing can be removed printf(“Error: Queue is Empty.”); exit(1); }

4

Page 5: Queues

else { --(Q->Count); // decrement count // increment Front by 1, if Zero is reach switch to MAX !!

Q->Front = (Q->Front + 1) % MAX; return ( Q->items [ Q->Front ] ); // Return the item at front } }

Queue: Linked-Based Representation Like the Linked-Based Stack, array items is replaced with a linked list! And, the functions

need to be re-implemented to work with the linked list Typedef char itemType; typedef struct qt{ itemType item; // Holds the item to be inserted struct qt * link; // Points to next node in Queue } QueueNode; // It is just a node !

We may use another structure to point to Front and Rear: typedef struct{ QNode * Front; QNode * Rear;

} Queue; Why two structures?

o item link item link o item link

B Q A

To Remove front item: 1. Return item at Q->Front->item 2. Move Q->Front to next node 3. Free the first node. Do not forget to have a pointer pointing to this first node at first place!

To insert item at Rear: 1. Create new node of type QNode 2. Link the new node at end 3. Let Q->Rear points to the new node Front Rear

The implementation of these functions are left as exercise

Queues vs. Stacks Stacks are a LIFO container

o Store data in the reverse of order received Queues are a FIFO container

o Store data in the order received Stacks then suggest applications where some sort of reversal or unwinding is desired. Queues suggest applications where service is to be rendered relative to order received. Stacks and Queues can be used in conjunction to compare different orderings of the same

data set. From an ordering perspective, then, Queues are the “opposite” of stacks

5

Page 6: Queues

o Easy solution to the palindrome problem

Easy Palindrome Check#include “Stack.h”;#include “Queue.h”;#include <iostream.h>using namespace std;int main(){

Stack S;Queue Q;char ch;cout << “Enter string to be tested as palindrome: “;while (cin >> ch){

S.push(ch);Q.addq(ch);

}bool pal = true;while (!Q.empty() && pal) {

pal = Q.front() == S.pop();Q.removeq();

}if (pal)

cout << “Palindrome!!” << endl;return 0;

}Deque

A deque (double-ended queue) is similar to a queue BUT additions and deletions may be performed on either end. The deque is a standard container provided by STL. It is easily implemented by the vector type.

Priority Queues Priority queues are queues in which items are ordered by priority rather than temporally (i.e.

order in which received). Any queue implementation then can be taken and modified to acquire a priority queue. The only needed modification is the addq() method. Instead of unconditionally adding to the back, the queue must be scanned for the correct

insertion point. An array implementation then would require shifting elements Hence a linked list implementation is preferred.

6