Linked List – descendingIterator() method in Java

The descendingIterator() method has been present since Java 1.6 and is used to iterate the linked list in the reverse order. In this post, we will discuss the descendingIterator() method of the Linked List class.

  • Method declaration – public Iterator descendingIterator()
  • What does it do? It helps in iterating the linked list in reverse order.
  • What does it return? It returns an iterator, which can be used to iterate over the linked list in reverse order.
Code Example

Let’s see things with an example code now, where we will use the descendingIterator() function.

import java.util.Iterator;
import java.util.LinkedList;

public class Codekru {

	public static void main(String[] args) {
		LinkedList<Object> linkedList = new LinkedList<>();

		// adding into the linked list
		linkedList.add("first");
		linkedList.add("second");
		linkedList.add("third");

		System.out.println("Linked List : " + linkedList);

		Iterator<Object> itr = linkedList.descendingIterator();

		System.out.print("Printing Linked List in reverse fashion: ");
		while (itr.hasNext()) {
			System.out.print(itr.next() + " ");
		}

	}
}

Output –

Linked List : [first, second, third]
Printing Linked List in reverse fashion: third second first 

Now, here you can see that the linked list is printed reversely.

Now, the question is that how does descendingIterator works?

Well, in the linked list class, there is another private class, DescendingIterator, which overrides the hasNext(), next() and remove() method. So, when we call itr.hasNext(), like in our code, it is executing itr.hasPrevious() behind the scenes, and the same goes for the next() method as well.

DescendingIterator class
    private class DescendingIterator implements Iterator<E> {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }
Internal implementation of the descendingIterator() method
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

Time complexity of the descendingIterator() method

The time complexity of the descendingIterator() is O(1) as it only returns a DescendingIterator object. Though afterward, it will take O(n) time to iterate over the Linked List, the descendingIterator() method itself runs on constant complexity of O(1).

Please visit this link to learn more about the linked list class and its methods.

We hope that you have liked this article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected]

Liked the article? Share this on

Leave a Comment

Your email address will not be published.