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?
ListNode head = theHead;
-- Just stick it in a variable before you traverse the list. - Jason C