Sequential Representation Representation of Queues

J.E.D.I

3.3.1 Sequential Representation

If the implementation uses sequential representation, a one-dimensional arrayvector is used, hence the size is static. The queue is empty if the front = rear and full if front=0 and rear=n. If the queue has data, front points to the actual front, while rear points to the cell after the actual rear. Deletion from an empty queue causes an underflow while insertion onto a full queue causes an overflow. The following figure shows an example of the ADT queue: Figure 1.15 Operations on a Queue Figure 1.16 To initialize, we set front and rear to 0: front = 0; rear = 0; To insert an item, say x, we do the following: Q[rear] = item; rear++; and to delete an item, we do the following: x = Q[front]; front++; To implement a queue using sequential representation: class SequentialQueue implements Queue{ Object Q[]; int n = 100 ; size of the queue, default 100 int front = 0; front and rear set to 0 initially int rear = 0; Create a queue of default size 100 SequentialQueue1{ Q = new Object[n]; } Create a queue of the given size SequentialQueue1int size{ n = size; Data Structures 41 J.E.D.I Q = new Object[n]; } Inserts an item onto the queue public void enqueueObject item throws QueueException{ if rear == n throw new QueueException Inserting into a full queue.; Q[rear] = item; rear++; } Deletes an item from the queue public Object dequeue throws QueueException{ if front == rear throw new QueueException Deleting from an empty queue.; Object x = Q[front]; front++; return x; } } Whenever deletion is made, there is space vacated at the “front-side” of the queue. Hence, there is a need to move the items to make room at the “rear-side” for future insertion. The method moveQueue implements this procedure. This could be invoked when void moveQueue throws QueueException{ if front==0 throw new QueueExceptionInserting into a full queue; forint i=front; in; i++ Q[i-front] = Q[i]; rear = rear - front; front = 0; } There is a need to modify the implementation of enqueue to make use of moveQueue: public void enqueueObject item{ if rear is at the end of the array if rear == n moveQueue; Q[rear] = item; rear++; }

3.3.2 Linked Representation