As we have done in previous sections, we will create a new class for the implementation of the abstract data type deque. Again, the Java ArrayList will provide a very nice set of methods upon which to build the details of the deque. Our implementation (Listing 3.17.1) will assume that the tail of the deque is at position 0 in the list.
d.isEmpty() | true | <<empty deque>>
d.addTail(4) | | tail [4] head
d.addTail(505) | | tail [505, 4] head
d.addHead(1066) | | tail [505, 4, 1066] head
d.addHead(4711) | | tail [505, 4, 1066, 4711] head
d.size | 4 | tail [505, 4, 1066, 4711] head
d.isEmpty() | false | tail [505, 4, 1066, 4711] head
d.addTail(217) | | tail [217, 505, 4, 1066, 4711] head
d.removeTail() | 217 | tail [505, 4, 1066, 4711] head
d.removeHead() | 4711 | tail [505, 4, 1066] head
You can see many similarities to Java code already described for stacks and queues. You are also likely to observe that in this implementation adding and removing items from the head is \(O(1)\) whereas adding and removing from the tail is \(O(n)\text{.}\) This is to be expected, given the common operations that appear for adding and removing items. Again, the important thing is to be certain that we know where the head and tail are assigned in the implementation.