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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *