Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top