简体   繁体   中英

How to get back to the head of a singly linked list after creating it in java?

I am writing a program to slice a number into its digits and to store the digits in a linked list in reverse order. But I am not able to understand how to return the linked list?

I have tried creating a head ListNode but failed in it.

public class ListNode {
   int val;
   ListNode next;
   ListNode(int x) { val = x; }
  }

class Solution{
  int sum=123;
  public ListNode sol(){
    answer = new ListNode(0);  
    while (sum > 0) {
     int digit = sum % 10;
     answer= new ListNode(digit);
     answer= answer.next;
     sum /= 10;
                    }
        return //////
  }
}

Here:

answer = new ListNode(0);  

That ListNode instance is the first element, and thus the "root" of your list. But your list is only singly linked. You can't get back to a previous element! You have to remember where it started!

In other words, you have two options:

  • turn your list into a double-linked list (so: each node remembers its predecessor) or
  • remember that root node.

In other words: when using answer as the "moving pointer" within your list, then you should do something like:

root = new ListNode(0); // remember this, it is the start of the list!
answer = root;

And then you have to ensure to keep root around and unchanged! Because that reference represents the (one and only!) entrance to your list data. When you lose that, everything is lost ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM