My understanding of traversing backwards in a doubly linked list is traversing from some position back to the first node in the list. I have written a Doubly Linked List class in java, and a traverseBack method in it.
The code for the traverseBack method is as follows.
public void traverseBack(int d){
for(Node n=first; n!=null; n=n.next){
if(n.data == d){
System.out.println("\nTraversing in Backward Direction\n");
while(n!=null){
System.out.println(n.data);
n = n.prev;
}
return;
}
if(n.next==null){
System.out.println("Given node doesn't exist");
return;
}
}
}
The code was compiled and run without errors.
Can I ask whether my understanding of traversing backwards in a doubly linked list is correct or not? Is there anything in the code that I haven't done well?
The mistake here is you do not seem to be going backward, you're going forward. You're iterating the Node
s in your for
loop by calling n=n.next
. Shouldn't you be calling n=n.prev
?
Why don't you just start with the last
element and loop backwards from there? You could go like this:
for(Node n=last; n!=null; n=n.prev){ //this is traversing backwards now.
Once you've done that, there's no need for the while
loop at all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.