Queue Implementation in Java Using LinkedList

In this guide, we'll explore how to use the LinkedList for implementing a Queue in Java. 

Queue Overview

A Queue operates on the First In First Out (FIFO) principle. Think of it as a real-world queue: the first person to join is the first to leave. 

Primary Operations: 

enqueue: Adds an item to the rear. 

dequeue: Removes and returns the front item. 

isEmpty: Checks if the queue is empty. 

front: Retrieves the front item without removing it. 

Java Queue Implementation Using LinkedList

Let's create our Queue:

import java.util.LinkedList;

public class QueueUsingLinkedList<T> {

    private LinkedList<T> list = new LinkedList<T>();

    // Add item to the end of the list
    public void enqueue(T item) {
        list.addLast(item);
    }

    // Remove and return item from the front
    public T dequeue() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        return list.removeFirst();
    }

    // Check if the queue is empty
    public boolean isEmpty() {
        return list.isEmpty();
    }

    // View the item at the front
    public T front() {
        return list.peekFirst();
    }
}

Testing the Queue:

public class Main {
    public static void main(String[] args) {
        QueueUsingLinkedList<Integer> queue = new QueueUsingLinkedList<>();

        queue.enqueue(10);
        queue.enqueue(20);
        queue.enqueue(30);

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

        queue.enqueue(40);
        queue.enqueue(50);

        System.out.println(queue.dequeue() + " dequeued from queue");
    }
}

Output:

10 dequeued from queue
Front item is 20
20 dequeued from queue

Pros of Using LinkedList for Queue Implementation

Performance: Both enqueue and dequeue operations are O(1) with a linked list. 

Dynamic Size: Unlike arrays, the size of the linked list grows and shrinks dynamically as needed. 

Inbuilt Functions: Java’s LinkedList class already has methods to act as the end and beginning of the queue. 

Conclusion

When implementing a queue in Java, using a LinkedList offers an efficient and dynamic approach. The LinkedList's inbuilt methods make the implementation straightforward, and the O(1) time complexity for the core operations ensures that performance remains optimal. It's an excellent choice for applications where queue operations are frequent and dynamic growth is essential.

Comments