120 likes | 249 Views
Queues. Introduction. A sequential collection of data Changes occur at both ends, not just one Queue applications files waiting to be printed "jobs" waiting for the CPU or an I/O device tokens waiting to be processed signals on a channel (wired or wireless) Simulations .
E N D
Introduction • A sequential collection of data • Changes occur at both ends, not just one • Queue applications • files waiting to be printed • "jobs" waiting for the CPU or an I/O device • tokens waiting to be processed • signals on a channel (wired or wireless) • Simulations
Structural Concept • A sequence of data items • Items may be ANY type • integers • chars • arrays • structs • Operations • Items can be removed only at the front • Items can be added only at the end • Only the front item may be viewed
Queue front enqueue dequeue index FIFO list - only front element is visible
The Queue ADT • Operations • Construct a queue • Test for queue is empty/full • Enqueue (add new item at end) • Front (retrieve value of item at front) • does not remove item • Dequeue (removeitem from front) • next item moves to the front
Static-Array Implementation • Operations & constants • Q_MAX specifies item total • enqueue • increments index • use mod operator to "circle back to start" • 1st checks for full queue • dequeue • increments index • uses mod operator to "circle back to start" • 1st checks for empty queue
myArray 7 6 5 4 3 2 1 0 myFront -1 Static-array Implementation Example typedefComplxQueueElement; constint CAPACITY = 8; intmyFront, myBack; QueueElementmyQueue[CAPACITY]; Complx X; enqueue(&myArray,X); myBack -1 initiallyempty (myFront, myBack are negative)
Caveats • could be too small • could be too large (wastes space) • must be careful managing index • solution (TBD) is dynamic storage • going past the "end"
Solutions • careful mgmt of index values (front, back) • bigger queue • circular queue • dynamic array (TBD)
Circular Queue • Each array element (a node) is 2 items • index of next node • data • Last node has index of first node • Or keep separate int index • subscript of "last" node • 1st node = MOD(lastnode+1,CAPACITY)
Some More Uses of a Queue • job scheduling • graphic display sequencing • disk I/O access • message processing • spaceship launch sequence • data "buffering"
Buffering • data produced faster than can be used • need to store it • storage is called a "buffer" • any stack or queue can be called a buffer