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

如何在Java单链表中实现append方法?连接逻辑存疑求助

单链表append方法的正确实现

你当前的代码逻辑存在问题:直接让head.next = list.head会丢弃当前链表头节点之后的所有节点,而且如果当前链表是空链表(head为null),还会触发空指针异常。正确的做法是找到当前链表的尾节点,再把传入链表的头节点接在尾节点后面。

另外要注意:append方法应该属于LinkedList类,而非内部的Node类——这是整个链表的操作,不是单个节点的行为。

修正后的代码如下:

public class LinkedList implements Singly {

    private Node head;

    private class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
            next = null;
        }
    }

    // 正确的append方法,归属LinkedList类
    public void append(LinkedList list) {
        // 传入链表为空时直接返回,无需操作
        if (list.head == null) {
            return;
        }

        // 当前链表为空时,直接复用传入链表的头节点
        if (this.head == null) {
            this.head = list.head;
            return;
        }

        // 遍历找到当前链表的尾节点(next为null的节点)
        Node current = this.head;
        while (current.next != null) {
            current = current.next;
        }

        // 将尾节点的next指向传入链表的头,完成拼接
        current.next = list.head;
    }
}

关键逻辑说明:

  • 空链表边界处理:先判断当前或传入链表是否为空,避免空指针异常,同时覆盖链表为空的特殊场景。
  • 遍历找尾节点:通过while循环遍历到链表最后一个节点(即next为null的节点),这才是拼接的正确位置。
  • 链表拼接:把尾节点的next指向传入链表的头节点,实现两个链表的连接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:55:21