Reputation: 83
Say there is a singly linked list: 1->2->3->4->null
Definition for singly-linked list:
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
If I want to print the node value one by one from head to tail, I need to use head = head.next iteratively until head == null. In this case, we can never return to the head(value=1) node after printing. My question is how to keep the head while traversing the singly linked list?
Upvotes: 4
Views: 2796
Reputation: 7624
Simple Answer: Create a reference to the head, and traverse that. That way you never lose that reference to the head.
Example:
ListNode iter = head;
while(iter.next != null){
//DO Stuff
iter = iter.next;
}
Note now that the head variable is never changed. It is ready to be used as before.
Upvotes: 9