Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the use of ListIterator.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to demonstrate the use of ListIterator.

Objective

Write a Java program to iterate over a List backwards using a ListIterator.

Algorithm / Approach

  1. Create a LinkedList and add items to it.
  2. Obtain the list's size.
  3. Create a ListIterator starting at the very end of the list: ll.listIterator(size).
  4. Use a while loop with the condition li.hasPrevious().
  5. Retrieve elements using li.previous() and print them.
Test.java
import java.util.*;
class Test {
 public static void main(String[] a)
 {
  LinkedList ll = new LinkedList();
  ll.add("Alok");
  ll.add("Daneyal");
  ll.add("Arif"); 
  ll.add("Ayan");
  int x = ll.size();
  ListIterator li=ll.listIterator(x);
  while(li.hasPrevious()) {
   System.out.print(li.previous()+"  ");
  }
 }
}

Expected Output

Ayan  Arif  Daneyal  Alok

Explanation of the Program

  • A normal Iterator can only move in one direction: forward.
  • A ListIterator is a more powerful sub-interface designed specifically for Lists. It allows you to traverse the list in both directions.
  • By initializing the cursor position at the very end of the list (using the size), we can use hasPrevious() and previous() to easily read the entire list in reverse order.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT