ADT Queues Definition:
Queues are ordered lists, which follow a FirstIn-First-Out (FIFO) order. These can be implemented as an array or using a dynamic memory allocation scheme. Queues are usually implemented using a circular array. The first element is known as the head and the last element is known as the tail.
Operations: 1. Enqueue
2. Dequeue 3. FullQ 4. Makenull
5. EmptyQ
1. Enqueue
{ if (NumItems == MaxQueue) Success = False; //queue is full else { Rear = (Rear + 1) % MaxQueue; //increment rear Q[Rear] = El; NumItems = NumItems + 1; Success = True; }
}
2. Dequeue { if (NumItems == 0) Success = False; //queue is empty else { //Remove the element at the front of the queue El = Q[Front]; Front = (Front + 1) % MaxQueue; //increment Front NumItems = NumItems - 1; Success = True; } }
3. Makenull {
NumItems = 0; Front = 0; Rear = MaxQueue - 1;
}
4. FullQ { return (NumItems == MaxQueue); } 5. EmptyQ { return (NumItems == 0); }
Queues- Example
• Print Jobs - All requests from workstations are enqueued to the print queue on a first come first served basis - The current (first) printjob is dequeued and sent to the printer for processing
Queue - Applications
• I/O Request Handling File server - Workstation (print, data access,etc.) • Telephone Call Handling • History functions in applications
Enqueue public class ArrayQueue implements Queue { // ... public void enqueue( Object o ) { if ( (rear + 1) % MAX != front ) { store[rear] = o; rear = (rear + 1) % MAX; } } // ... }
Dequeue public class ArrayQueue implements Queue { // ... public Object dequeue() throws Exception { if ( empty() ) { throw new Exception(); } else { Object data = store[front]; store[front] = null; front = (front + 1) % MAX; return data; } } }
Using the Queue
Queue q = new ArrayQueue(); int result; // the following should be enclosed in a try-catch stmt q.enqueue( new Integer(5) ); q.enqueue( new Integer(2) ); result = ((Integer)q.dequeue()).intValue();