I m new to Java Collections and my doubt is why can't i traverse a element in linkedlist in backward directions.Below I'll explain what i did and please clarify my doubts.
Can't i use iterator and listiterator interface in the same program to traverse a set of elements in forward and backward iterations ?
Code Snippet :
import java.util.*;
class NewClass{
public static void main(String args[]){
LinkedList<String> obj = new LinkedList<String>();
obj.add("vino");
obj.add("ajith");
obj.add("praveen");
obj.add("naveen");
System.out.println(obj);
System.out.println("For loop ");
//using for loop
for(int count=0; count < obj.size(); count++){
System.out.println(obj.get(count));
}
System.out.println("For each loop ");
//using foreach loop
for(String s:obj){
System.out.println(s);
}
System.out.println("Whileloop ");
//using whileloop
int count=0;
while(obj.size() > count){
System.out.println(obj.get(count));
count++;
}
System.out.println("Forward Iterations ");
//using iterator
Iterator it = obj.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
ListIterator lit = obj.listIterator();
System.out.println("Backward Iterations");
while(lit.hasPrevious()){
System.out.println(lit.previous());
}
}
}
Output
[vino, ajith, praveen, naveen]
For loop
vino
ajith
praveen
naveen
For each loop
vino
ajith
praveen
naveen
Whileloop
vino
ajith
praveen
naveen
Forward Iterations
vino
ajith
praveen
naveen
Backward Iterations
Where is the output for Backward Iterations? Please anyone help me.Thanks in advance
A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in a LinkedList. The method hasPrevious( ) in ListIterator returns true if there are more elements in the LinkedList while traversing in the reverse direction and false otherwise.
To do the reverse printing we can simply pass the instance to list , and pass the resulting list to reversed , which returns an iterator that iterates backwards over its list argument.
It is not possible to reverse a simple singly linked list in less than O(n). A simple singly linked list can only be reversed in O(n) time using recursive and iterative methods.
I think you want a descendingIterator
.
Iterator lit = obj.descendingIterator();
System.out.println("Backward Iterations");
while(lit.hasNext()){
System.out.println(lit.next());
}
You can do it, but you need to use the method listIterator(int index)
to specify that you want to start at the end of the List
.
LinkedList<String> obj = new LinkedList<String>();
obj.add("vino");
obj.add("ajith");
obj.add("praveen");
obj.add("naveen");
ListIterator<String> it = obj.listIterator(obj.size());
while (it.hasPrevious())
System.out.println(it.previous());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With