Skip to content

Iterate LinkedList in Reverse Direction in Java Example

This example shows how to iterate LinkedList in reverse direction in Java. This example also shows how to iterate LinkedList in backward direction using ListIterator and descendingIterator method.

How to iterate LinkedList in reverse direction in Java?

There are a couple of ways using which you can iterate a LinkedList object in the reverse direction.

1. Using the ListIterator

A ListIterator in Java is an iterator that allows us to traverse the list in both directions. You can obtain a list iterator for the LinkedList object using the listIterator method.

The listIterator method returns an object of the ListIterator starting from the specified index argument.

For iterating the linked list in reverse or backward direction, we need to pass the argument index as the LinkedList size. This way, the list iterator’s cursor will be positioned at the end of the list, and from there we will iterate the list backward towards the start.

Once you get the list iterator, iterate the LinkedList using the hasPrevious and previous methods as given below.

Output

2. Using the descendingIterator method

The descendingIterator method of the LinkedList class returns an iterator over the linked list elements in reverse sequential order.

The iterator object returned by this method will return elements in the reverse order, from last to first or tail to head. Once you get an iterator object, use the hasNext and the next methods of the Iterator in Java to iterate the linked list in the backward direction.

Output

This example is a part of the LinkedList in Java tutorial.

Please let me know your views in the comments section below.

References:
Java 8 LinkedList

About the author

Leave a Reply

Your email address will not be published.