我正在尝试一个leetcode问题,我需要在java中实现一个链表,但是“链接”永远不会被创建。节点本身确实会被创建,但会丢失在内存中。我知道如何在c++中使用指针来实现这一点,但是在java中如何实现呢?
问题是:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

印刷品:
7
0
8

返回:
7 (just head node)

我的代码:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        //hold root node to return later, use temp node (l3) to create list
        ListNode head = new ListNode(0);
        ListNode l3 = head;

        boolean carryover = false;

        //if lists l1, l2 still have a value, append to l3
        while (l1 != null || l2 != null)
        {
            //always true except on first iteration
            if (l3 == null)
                l3 = new ListNode(0);

            //if l1.val + l2.val >= 10 from last iteration, carry over 1
            if (carryover)
            {
                l3.val += 1;
                carryover = false;
            }

            if (l1 != null)
            {
                l3.val += l1.val;
                l1 = l1.next;
            }

            if (l2 != null)
            {
                l3.val += l2.val;
                l2 = l2.next;
            }

            if (l3.val > 9)
            {
                l3.val -= 10;
                carryover = true;
            }
            System.out.println(l3.val);

            //create next 'link' in list
            l3 = l3.next;
        }
        return head;
    }
}

最佳答案

l3 = l3.next;没有做你认为正在做的事情。
l3.nextnull,因此您将null分配给l3null在内存中不是一个特殊的位置,它只是指l3.next,这意味着它没有指向任何东西。
所以在下一个循环中,当您执行null时,您只是创建一个断开连接的节点。
您应该首先确保l3 = new ListNode(0);指向一个节点,然后才能使用它。
所以,试试这个:

boolean first = true;

//if lists l1, l2 still have a value, append to l3
while (l1 != null || l2 != null)
{
    // create the next node
    if (!first) {
        // create the next node and attach it to the current node
        l3.next = new ListNode(0);
        // we now work with the next node
        l3 = l3.next;
    } else {
        first = false;
    }

    //if l1.val + l2.val >= 10 from last iteration, carry over 1
    if (carryover)
    {
        l3.val += 1;
        carryover = false;
    }

    if (l1 != null)
    {
        l3.val += l1.val;
        l1 = l1.next;
    }

    if (l2 != null)
    {
        l3.val += l2.val;
        l2 = l2.next;
    }

    if (l3.val > 9)
    {
        l3.val -= 10;
        carryover = true;
    }
    System.out.println(l3.val);

}

10-04 11:43