链接列表实现不形成链接(Java)



我正在尝试一个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);时,您只是创建一个断开的节点。

您应该首先确保next指向节点,只有这样您才能使用。

所以,尝试一下:

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);
}

用于合并两个列表,每个列表由第一个节点(head(

定义
private Node merge(Node list1, Node list2){
    if (list1.next == null && list2.next == null)
        return new Node(0);
    else if (list1.next == null)
        return list2;
    else if (list2.next == null)
        return list1;
    else {
        Node curr = list1.next;
        while (curr.next != null){
            curr = curr.next;
        }
        curr.next = list2.next;
        return list1;
    }
}

最新更新