Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep the head of a singly linked list in Java

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?

like image 280
user3390265 Avatar asked Oct 17 '25 13:10

user3390265


1 Answers

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.

like image 53
Sinkingpoint Avatar answered Oct 19 '25 02:10

Sinkingpoint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!