Module 6 - Queue
Module 6 - Queue
Dequeue Operation
• check if the queue is empty
• return the value pointed by FRONT
• increase the FRONT index by 1
• for the last element, reset the values of FRONT and REAR to -1
Illustration of Queue Data Structure (1)
Illustration of Queue Data Structure (2)
Illustration of Queue Data Structure (3)
Limitations of Queue Data Structure
• As can be seen in the image below, after a bit of enqueuing and dequeuing, the size
of the queue has been reduced.
• And we can only add indexes 0 and 1 only when the queue is reset (when all the
elements have been dequeued).
• After REAR reaches the last index, if we can store extra elements in the empty
spaces (0 and 1), we can make use of the empty spaces. This is implemented by a
modified queue called the circular queue.
Complexity Analysis and Applications of Queue
Complexity Analysis
The complexity of enqueue and dequeue operations is
Applications
• CPU scheduling, Disk Scheduling
• When data is transferred asynchronously between two processes, the queue
is used for synchronization. For example: IO Buffers, pipes, file IO, etc
• Handling of interrupts in real-time systems.
• Call Center phone systems use Queues to hold people calling them in order.
// Queue implementation in Java
public class Queue {
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;
Queue() {
front = -1;
rear = -1;
}
// Queue implementation in Java Cont’d
boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}
boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}
// Queue implementation in Java Cont’d
void enQueue(int element) {
if (isFull()) {
System.out.println("Queue is full");
} else {
if (front == -1)
front = 0;
rear++;
items[rear] = element;
System.out.println("Inserted " + element);
}
}
int deQueue() {
int element;
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
} else {
element = items[front];
if (front >= rear) {
front = -1;
rear = -1;
} /* Q has only one element, so we reset the queue after deleting it. */
else {
front++;
}
System.out.println("Deleted -> " + element);
return (element);
}
}
void display() {
/* Function to display elements of Queue */
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("\nFront index-> " + front);
System.out.println("Items -> ");
for (i = front; i <= rear; i++)
System.out.print(items[i] + " ");