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?
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.
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