Skip to main content

Queue Implementation

A Queue is a linear data structure that follows the FIFO (First In First Out) or LILO (Last In Last Out) principle. Elements are inserted at the rear and removed from the front.

Operations

  • Enqueue (Add): Adds an item to the queue. O(1)
  • Dequeue (Remove): Removes an item from the queue. O(1)
  • Peek / Front: Gets the element at the front. O(1)

Visual Representation

Array Based Implementation in Java

public class QueueArray {
private int capacity;
private int front, rear, size;
private int[] array;

public QueueArray(int capacity) {
this.capacity = capacity;
front = this.size = 0;
rear = capacity - 1;
array = new int[capacity];
}

public boolean isFull() {
return (size == capacity);
}

public boolean isEmpty() {
return (size == 0);
}

public void enqueue(int item) {
if (isFull()) {
System.out.println("Queue is Full");
return;
}
rear = (rear + 1) % capacity;
array[rear] = item;
size = size + 1;
System.out.println(item + " enqueued.");
}

public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is Empty");
return Integer.MIN_VALUE;
}
int item = array[front];
front = (front + 1) % capacity;
size = size - 1;
return item;
}

public int front() {
if (isEmpty()) return Integer.MIN_VALUE;
return array[front];
}

public static void main(String[] args) {
QueueArray queue = new QueueArray(3);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);

System.out.println(queue.dequeue() + " dequeued from queue\n");
System.out.println("Front item is " + queue.front());
}
}

Note: Java's standard library provides a java.util.Queue interface which is typically implemented by LinkedList or PriorityQueue.