Deque Iterator: Traversal and descendingIterator
You'll learn how to iterate through a deque in both directions—from head to tail using the standard iterator, and from tail to head using descendingIterator().
Two Ways to Walk Through a Deque
A deque gives you two types of iterators because it's double-ended. Think of it like a line of people where you can count from the front to the back, or from the back to the front.
The standard iterator traverses from head (first element) to tail (last element), just like walking forward through a queue. The descending iterator does the opposite—it starts at the tail and moves toward the head, like rewinding through the elements.
Standard Iterator: Head to Tail
When you call iterator() on a deque, you get an iterator that starts at the first element and moves toward the last:
Deque<String> deque = new LinkedList<>();
deque.addLast("A");
deque.addLast("B");
deque.addLast("C");
Iterator<String> iter = deque.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
// Output: A, B, C
Descending Iterator: Tail to Head
The descendingIterator() method returns an iterator that traverses in reverse order, starting from the last element:
Iterator<String> descIter = deque.descendingIterator();
while (descIter.hasNext()) {
System.out.println(descIter.next());
}
// Output: C, B, A
This is particularly useful when you need to process elements in reverse without modifying the deque structure itself.
Why Two Iterators?
Since deques support operations at both ends, it's natural to support iteration in both directions. You might use descendingIterator() to undo operations, display history in reverse order, or implement backward traversal algorithms.
Key Takeaway: Use iterator() to traverse a deque from head to tail, and descendingIterator() to traverse from tail to head—both without modifying the deque's structure.