简体   繁体   English

在Java中创建单链列表后,如何回到单链列表的开头?

[英]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. 我尝试创建一个头ListNode,但失败了。

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. ListNode实例是第一个元素,因此是列表的“根”。 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: 换句话说:当使用answer作为列表中的“移动指针”时,您应该执行以下操作:

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! 然后,您必须确保保持root和不变! Because that reference represents the (one and only!) entrance to your list data. 因为该引用代表列表数据的(唯一!)入口。 When you lose that, everything is lost ;-) 当您丢失它时,一切都将丢失;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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