简体   繁体   English

Java:在while循环中制作链表

[英]Java: Making a linked list in a while loop

I am trying to make an int (like 123) into a linked list.我正在尝试将一个 int(如 123)变成一个链表。 For example: 123 would result in a linked list of 3 -> 2 -> 1. My issue is that I am able to get each part of the number(like 3 or 2) but I can't seem to make the linked list.例如:123 将导致 3 -> 2 -> 1 的链表。我的问题是我能够获得数字的每个部分(如 3 或 2),但我似乎无法制作链表.

Here is my while Loop:这是我的while循环:

        value = Integer.parseInt(l1StrRev) + Integer.parseInt(l2StrRev);
        result = new ListNode(value % 10);
        value = value / 10;
        while(value > 0) {
            int newVal = value % 10;
            result.next = new ListNode(newVal);
            result = result.next;
            value = value / 10;
        }

I am getting back a linked-list of just one node with the most recent value.我取回了一个只有一个具有最新值的节点的链表。

In your code, you are updating the "result" variable too.在您的代码中,您也在更新“结果”变量。 So when u return the "result" variable, its actually pointing to the last Node.所以当你返回“result”变量时,它实际上指向最后一个节点。 I would suggest, before the while loop do a resultCopy = result.我建议,在 while 循环之前做一个 resultCopy = result。 And then in the end return resultCopy.然后最后返回resultCopy。 This way, resultCopy stores the head node of the list, and "result" acts as a temporary node as in ur code.这样,resultCopy 存储了列表的头节点,而“result”在你的代码中充当临时节点。

Looks like you are missing and mixed up a couple of lines.看起来您缺少并混淆了几行。 In your loop it should be something like...在你的循环中它应该是这样的......

  • Create a new node创建一个新节点

    Node node = new ListNode(newVal);

  • Set node.next to the result在结果旁边设置 node.next

    node.next = result;

  • Your result then becomes the new node above您的结果将成为上面的新节点

    result = node;

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

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