Mark As Completed Discussion

Another common way to implement a queue is using linked lists. In the linked list implementation, each element in the queue is represented as a node in a linked list, and the front and rear pointers are used to keep track of the first and last nodes, respectively.

Here's an example of how to implement a queue using linked lists in Java:

TEXT/X-JAVA
1class LinkedListQueue<T> {
2  private static class Node<T> {
3    private T data;
4    private Node<T> next;
5
6    public Node(T data) {
7      this.data = data;
8      this.next = null;
9    }
10  }
11
12  private Node<T> front;
13  private Node<T> rear;
14
15  public LinkedListQueue() {
16    this.front = null;
17    this.rear = null;
18  }
19
20  public void enqueue(T item) {
21    Node<T> newNode = new Node<>(item);
22
23    if (isEmpty()) {
24      front = newNode;
25    } else {
26      rear.next = newNode;
27    }
28
29    rear = newNode;
30  }
31
32  public T dequeue() {
33    if (isEmpty()) {
34      throw new NoSuchElementException("Queue is empty");
35    }
36
37    T data = front.data;
38    front = front.next;
39
40    if (front == null) {
41      rear = null;
42    }
43
44    return data;
45  }
46
47  public boolean isEmpty() {
48    return front == null;
49  }
50}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment