// This queue implementation uses a linked list and can dynamically grow and shrink as needed.
public class LinkedListQueue {
// Node class for linked list
private class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
private Node front; // Points to the front node
private Node rear; // Points to the rear node
private int size; // Number of elements in the queue
// Constructor to initialize an empty queue
public LinkedListQueue() {
front = null;
rear = null;
size = 0;
}
// Add an item to the rear of the queue
public void enqueue(int item) {
Node newNode = new Node(item);
if (isEmpty()) {
front = newNode;
} else {
rear.next = newNode;
}
rear = newNode;
size++;
}
// Remove and return the front item of the queue
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot dequeue.");
return Integer.MIN_VALUE;
}
int item = front.data;
front = front.next;
if (front == null) {
rear = null; // Reset rear when queue becomes empty
}
size--;
return item;
}
// Return the front item without removing it
public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty. No peek value.");
return Integer.MIN_VALUE;
}
return front.data;
}
// Return true if the queue is empty
public boolean isEmpty() {
return front == null;
}
// Return the number of elements in the queue
public int size() {
return size;
}
// Print the current state of the queue
public void printState(String stepTitle, String enqueueItems, Integer dequeued) {
System.out.println("------------" + stepTitle + "---------------");
if (enqueueItems != null) {
System.out.println("Enqueue: " + enqueueItems + ";");
}
if (dequeued != null) {
System.out.println("Dequeued: " + dequeued + ";");
}
System.out.println("Current size: " + size);
System.out.println("Peek value: " + (isEmpty() ? "N/A" : peek()));
// Mimic array-like content display
System.out.print("Linked list content: ");
Node current = front;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
// Show visible queue (same as content in linked list)
System.out.print("\nVisible queue: ");
current = front;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println("\n");
}
// Demonstration of linked list queue operations
public static void main(String[] args) {
LinkedListQueue queue = new LinkedListQueue();
// Step 1: Enqueue multiple elements
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.printState("Step 1 : enqueue", "10, 20, 30", null);
// Step 2: Dequeue one element
int removed = queue.dequeue();
queue.printState("Step 2 : dequeue", null, removed);
// Step 3: Enqueue additional elements
queue.enqueue(40);
queue.enqueue(50);
queue.enqueue(60);
queue.printState("Step 3 : enqueue", "40, 50, 60", null);
}
}