Write a Java program to traverse the elements of a LinkedList in reverse direction


The LinkedList_Reverse class contains a main method where a linked list of strings, col_list, is created and populated with some values using the add method. The col_list contains the strings "Blue", "Green", "Pink", "Black", "Red", and "Orange".

The descendingIterator method is called on the col_list linked list to get an iterator that iterates over the elements in the reverse order. The hasNext and next methods of the iterator are used in a while loop to iterate over the elements in the reverse order and print them using System.out.println.

As a result, the elements in the linked list are printed in reverse order, with "Orange" being the first element printed and "Blue" being the last element printed.

Source Code

import java.util.*;
public class LinkedList_Reverse
{
    public static void main(String[] args)
    {
		LinkedList<String> col_list = new LinkedList<String>(); 
		col_list.add("Blue");
		col_list.add("Green");
		col_list.add("Pink");
		col_list.add("Black");
		col_list.add("Red");
		col_list.add("Orange");  
		System.out.println(col_list); 
		Iterator<String> cl = col_list.descendingIterator(); 
		while (cl.hasNext())
		{
			System.out.println(cl.next());
		}
    }
}

Output

[Blue, Green, Pink, Black, Red, Orange]
Orange
Red
Black
Pink
Green
Blue

Example Programs