LinkedList descendingIterator run time.

I couldn’t find the run time performance of LinkedList’s descendingIterator(), so I decided to roll up my sleves and investigate.

Theory 1: Linked list has to traverse to the end of the list to get the last node, so run time would be O(n).
Theory 2: Linked list keeps track of the last node and uses it. This would be O(1).

TL;DR; Getting Iterator has O(1) performance.

Reason:

Background: Descending iterator is useful if you want to iterate over a list backwards:


LinkedList myList = new LinkedList(); 
LinkedList myList = new LinkedList(); 
myList.add(1); 
myList.add(2); 
myList.add(3); 
Iterator myDescIter = myList.descendingIterator(); 
while (myDescIter.hasNext()) { 
   System.out.println(myDescIter.next()); 
}

 

I hunted around Java’s source code to investigate.
LinkedList has 2 internal references:

transient Node first;
transient Node last;

But it’s not actually referencing those until you call ‘iter.next()’.
When next() is called, it is redirected to previous();

private class DescendingIterator implements Iterator<E> {
 private final ListItr itr = new ListItr(size());
 public boolean hasNext() {
      return itr.hasPrevious();
 }

Which in turn returns the last node:

</pre>
public E previous() {
....
lastReturned = next = (next == null) ? last : next.prev;   // next == null -&gt; we get 'last'
<pre>

So in Theory 2 is correct, we start form the last node and thus get O(1).

As a side node, if you add a node after getting the iterator, and then use the iterator, you get an  excepiton. So make sure to only get the iterator when you need it!

Leave a Reply