To implement the enqueue() and dequeue() methods in Java, follow these steps:
- Using a double linked list, implement the dequeue and enqueue pseudocode shown in the preceding code in Java. Follow the structure and method signature shown in the following code snippet:
public class Queue<V> {
private DblLinkedListNode<V> head;
private DblLinkedListNode<V> tail;
public void enqueue(V item)
public Optional<V> dequeue()
}
Snippet 2.20: Exercise class structure and method signatures
- The enqueue() method can be implemented as shown in the following code:
public void enqueue(V item) {
DblLinkedListNode<V> node = new DblLinkedListNode<>(item, null, tail);
Optional.ofNullable(tail).ifPresent(n -> n.setNext(node));
tail = node;
if(head == null) head = node;
}
Snippet 2.21: Exercise class structure and method signatures. Source class name: Queue
Queues are dynamic data structures that have a FIFO ordering. In the next section, we shall explore another data structure with a different ordering called a stack.