You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现链表时无法建立节点链接的问题求助

Fixing Java Linked List Linking Issues for LeetCode's Add Two Numbers Problem

Hey there! I totally get where you're coming from—switching from C++ pointers to Java's reference model can trip up even experienced devs when working with linked lists. Let's break down why your nodes are "disappearing" and fix that add-two-numbers implementation.

First: The Key Difference Between C++ Pointers and Java References

In C++, you explicitly manage pointers to link nodes (current->next = new ListNode(...)). In Java, there are no pointers—everything's a reference. When you assign current.next = new ListNode(...), you're telling the current node's next field to reference the new node you just created. The catch? You need to keep updating your "current" reference to track the end of your list, otherwise those new nodes won't be connected to your main chain (and will get garbage-collected, hence "disappearing").

Why Your Code Was Only Returning the Head Node

From what you described—you can print 7 0 8 but only return the head node 7—it sounds like you weren't properly linking the subsequent nodes to the head's chain. Maybe you created the 0 and 8 nodes but never set the previous node's next field to point to them, or you didn't track the end of the list as you built it.

The Correct Java Implementation

Let's build this step by step, using a dummy head node to simplify the logic (no more checking if the head is null!):

First, the standard ListNode definition (matches what LeetCode uses):

public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

Then the solution function:

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // Dummy head acts as a placeholder—we'll return dummy.next as the real head
        ListNode dummyHead = new ListNode(0);
        // Current keeps track of the last node in our result list
        ListNode current = dummyHead;
        int carry = 0;

        // Loop until we've processed all nodes in both lists and there's no carry left
        while (l1 != null || l2 != null || carry != 0) {
            // Get values from current nodes (0 if the list is exhausted)
            int value1 = (l1 != null) ? l1.val : 0;
            int value2 = (l2 != null) ? l2.val : 0;

            // Calculate sum and carry for this digit
            int total = value1 + value2 + carry;
            carry = total / 10;
            int currentDigit = total % 10;

            // Create a new node for the digit, link it to the end of the result list
            current.next = new ListNode(currentDigit);
            // Move current to the new end of the list
            current = current.next;

            // Advance the pointers in the input lists
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }

        // The real head is the first node after the dummy
        return dummyHead.next;
    }
}

Test It Out

Here's how to verify it works with your example input:

public class Main {
    public static void main(String[] args) {
        // Build list 1: 2 -> 4 -> 3
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);

        // Build list 2: 5 -> 6 -> 4
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);

        Solution sol = new Solution();
        ListNode result = sol.addTwoNumbers(l1, l2);

        // Print the result: 7 0 8
        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
    }
}

What's Different Here?

  • Dummy Head: Eliminates the hassle of checking if the result list is empty when adding the first node.
  • Current Reference: We always update current to point to the latest node in the result list. This ensures every new node is linked to the chain, so none get lost to garbage collection.
  • Carry Handling: We keep processing until there's no carry left, which handles cases where the sum has an extra digit (like 999 + 1 = 1000).

This implementation will correctly return the full linked list (7 -> 0 -> 8), not just the head node, and print all values as expected.

内容的提问来源于stack exchange,提问作者Gyn Manstot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:08:16