A circular queue implemented with an ArrayList
in Java uses fixed start and end points that wrap around the list, allowing efficient use of space by reusing array slots. It maintains the first-in-first-out (FIFO) order by incrementing head and tail indices modulo the array size.
Solutions:
import java.util.ArrayList;
class CircularQueue {
private ArrayList<Integer> queue;
private int maxSize;
private int front;
private int rear;
private int currentSize;
// Constructor
public CircularQueue(int size) {
this.maxSize = size;
this.queue = new ArrayList<>(size);
this.front = 0;
this.rear = -1;
this.currentSize = 0;
// Initialize the array list with null values
for (int i = 0; i < size; i++) {
queue.add(null);
}
}
// Enqueue operation
public void enqueue(int data) {
if (isFull()) {
System.out.println("Queue is full. Cannot add " + data);
return;
}
rear = (rear + 1) % maxSize;
queue.set(rear, data);
currentSize++;
}
// Dequeue operation
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot dequeue.");
return -1;
}
int data = queue.get(front);
queue.set(front, null); // Optional: Reset the value to null
front = (front + 1) % maxSize;
currentSize--;
return data;
}
// Check if the queue is full
public boolean isFull() {
return currentSize == maxSize;
}
// Check if the queue is empty
public boolean isEmpty() {
return currentSize == 0;
}
// Display the queue
public void display() {
System.out.print("Queue: ");
for (int i = 0; i < maxSize; i++) {
if (queue.get(i) != null) {
System.out.print(queue.get(i) + " ");
} else {
System.out.print("_ ");
}
}
System.out.println();
}
}
public class QueueAL {
public static void main(String[] args) {
CircularQueue queue = new CircularQueue(5); // Create a circular queue of size 5
queue.enqueue(10); // Add 10
queue.enqueue(20); // Add 20
queue.enqueue(30); // Add 30
queue.enqueue(40); // Add 40
queue.enqueue(50); // Add 50
System.out.println("Initial Queue:");
queue.display(); // Display the queue
queue.enqueue(60); // Attempt to add 60 (queue is full)
System.out.println("Dequeue operation: " + queue.dequeue()); // Remove and print front element
System.out.println("Queue after one dequeue operation:");
queue.display(); // Display the queue
queue.enqueue(60); // Add 60 (queue has space now)
System.out.println("Queue after enqueue operation:");
queue.display(); // Display the queue
while (!queue.isEmpty()) { // Dequeue all elements
System.out.println("Dequeue operation: " + queue.dequeue());
}
System.out.println("Queue after dequeuing all elements:");
queue.display(); // Display the queue
queue.dequeue(); // Attempt to dequeue from empty queue
}
}