It is again appropriate to create a new class for the implementation of the abstract data type queue. As before, we will use the power and simplicity of the ArrayList collection to build the internal representation of the queue.
We need to decide which end of the list to use as the tail and which to use as the head. The implementation shown in Listing 3.12.1 assumes that the tail is at position 0 in the list. This allows us to use the add function on lists to add new elements to the tail of the queue. The remove operation can be used to remove the head element (the last element of the list). Recall that this also means that enqueue will be \(O(n)\) and dequeue will be \(O(1)\text{.}\)
Listing 3.12.2 shows the Queue class in action as we perform the sequence of operations from Section 3.11.
ExercisesSelf Check
1.
Suppose you have the following series of queue operations.
Queue<String> q = new Queue<>()
q.enqueue("hello");
q.enqueue("dog");
q.enqueue("cat");
q.dequeue();
What items are left on the queue (from head to tail)?
"hello", "dog"
Remember the first thing added to the queue is the first thing removed. FIFO
"dog", "cat"
Yes, first in first out means that "hello" is gone
"hello", "cat"
Queues and stacks are both data structures where you can only access the first and the last items.
"hello", "dog", "cat"
Ooops, maybe you missed the dequeue call at the end?