This Java Example shows how to iterate through a LinkedList object in reverse direction using Java ListIterator's previous and hasPrevious methods .
import java.util.LinkedList; import java.util.ListIterator; public class TraverseReverseUsingListIteratorExample { public static void main(String[] args) { // create an LinkedList object LinkedList lList = new LinkedList(); // Add elements to Linkedlist lList.add("1"); lList.add("2"); lList.add("3"); /** * listIterator(int index) - Returns a list iterator of the elements in * this list (in proper sequence), starting at the specified position in * this list.An initial call to the previous method would return the * element with the specified index minus one. **/ ListIterator listIterator = lList.listIterator(lList.size()); System.out.println("Linkedlist in the reverse order: "); while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); } } }
The output is:
Linkedlist in the reverse order:
3
2
1
No comments:
Post a Comment