|
| 1 | +/** |
| 2 | + * An implementation of the queue data structure based on linked list. |
| 3 | + * |
| 4 | + * <p> |
| 5 | + * This implementation is basically a linked list with a tail, where the head |
| 6 | + * of the list is the front of the queue and the tail is the rear. Both the head |
| 7 | + * and the tail are empty nodes themselves. The rear (the last enqueued element) |
| 8 | + * points to the tail and the tail points back to the rear, forming a cycle. |
| 9 | + * This helps achieve both enqueueing and dequeueing in constant time. |
| 10 | + * |
| 11 | + * <p> |
| 12 | + * Operations with their complexities are: |
| 13 | + * <ul> |
| 14 | + * <li><code>enqueue</code>: O(1)</li> |
| 15 | + * <li><code>dequeue</code>: O(1)</li> |
| 16 | + * <li><code>peek</code>: O(1)</li> |
| 17 | + * </ul> |
| 18 | + */ |
| 19 | +public class Queue<T> { |
| 20 | + private LinkedListNode<T> head; |
| 21 | + private LinkedListNode<T> tail; |
| 22 | + private int length; |
| 23 | + |
| 24 | + public Queue() { |
| 25 | + this.head = new LinkedListNode<T>(null, null); |
| 26 | + this.tail = new LinkedListNode<T>(null, this.head); |
| 27 | + this.head.next = this.tail; |
| 28 | + this.length = 0; |
| 29 | + } |
| 30 | + |
| 31 | + public Queue(T[] data) { |
| 32 | + this.head = new LinkedListNode<T>(null, null); |
| 33 | + this.tail = new LinkedListNode<T>(null, this.head); |
| 34 | + this.head.next = this.tail; |
| 35 | + this.length = 0; |
| 36 | + |
| 37 | + for (T d: data) |
| 38 | + this.enqueue(d); |
| 39 | + } |
| 40 | + |
| 41 | + public int getLength() { |
| 42 | + return this.length; |
| 43 | + } |
| 44 | + |
| 45 | + public boolean isEmpty() { |
| 46 | + return this.length == 0; |
| 47 | + } |
| 48 | + |
| 49 | + public Queue<T> enqueue(T data) { |
| 50 | + this.tail.next.next = new LinkedListNode<T>(data, this.tail); |
| 51 | + this.tail.next = this.tail.next.next; |
| 52 | + |
| 53 | + this.length++; |
| 54 | + return this; |
| 55 | + } |
| 56 | + |
| 57 | + public Queue<T> dequeue() { |
| 58 | + if (this.length == 0) return this; |
| 59 | + |
| 60 | + this.head.next = this.head.next.next; |
| 61 | + |
| 62 | + this.length--; |
| 63 | + if (this.length == 0) this.tail.next = this.head; |
| 64 | + return this; |
| 65 | + } |
| 66 | + |
| 67 | + public T peek() { |
| 68 | + return this.head.next.data; |
| 69 | + } |
| 70 | +} |
0 commit comments