Java Program to demonstrate the use of ListIterator.
Objective
Write a Java program to iterate over a List backwards using a ListIterator.
Algorithm / Approach
- Create a
LinkedListand add items to it. - Obtain the list's size.
- Create a
ListIteratorstarting at the very end of the list:ll.listIterator(size). - Use a
whileloop with the conditionli.hasPrevious(). - 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
Iteratorcan only move in one direction: forward. - A
ListIteratoris 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()andprevious()to easily read the entire list in reverse order.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)