Write a Java program to iterate a linked list in reverse order


This Java code demonstrates how to use the descendingIterator() method to iterate over a linked list in reverse order.

  • The code defines a class named Iterate_Reverse with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a new LinkedList object named book_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Java", "C", "Cpp", etc., are added to the book_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the initial contents of the book_list before any modifications.
  • The descendingIterator() method is called on the book_list to obtain an iterator that allows iterating over the elements of the list in reverse order. The descendingIterator() method returns an iterator that starts from the last element of the list and iterates towards the first element.
  • Inside the while loop, the it.hasNext() method is called to check if there are more elements in the iterator. If true, the it.next() method is called to retrieve the next element from the iterator, and it is printed using the System.out.println statement.
  • The loop continues until there are no more elements in the iterator, effectively iterating over the book_list in reverse order.
  • The output of the program will be the initial contents of the book_list printed on the first line, followed by the elements of the list printed in reverse order, each on a separate line.

Source Code

import java.util.LinkedList;
import java.util.Iterator;
public class Iterate_Reverse
{
	public static void main(String[] args)
	{
		LinkedList<String> book_list = new LinkedList<String>();
		book_list.add("Java");
		book_list.add("C");
		book_list.add("Cpp");
		book_list.add("Python");
		book_list.add("Php");
		book_list.add("Css");
		book_list.add("Html");
		book_list.add("MySql");
		System.out.println("linked list:" + book_list);
		Iterator it = book_list.descendingIterator();
		System.out.println("Reverse Order:");
		while (it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}

Output

linked list:[Java, C, Cpp, Python, Php, Css, Html, MySql]
Reverse Order:
MySql
Html
Css
Php
Python
Cpp
C
Java

Example Programs