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

Java单链表两个实例无法独立打印问题求助

问题:创建两个单链表实例却输出同一链表内容

我的代码实现

public class MergeSinglyLinkedList {

    private static ListNode head; // 问题根源在这里

    private static class ListNode {
        private int data;
        private ListNode next;

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

    public static void main(String[] args) {
        MergeSinglyLinkedList sll1 = new MergeSinglyLinkedList();
        sll1.insertAtLast(1);
        sll1.insertAtLast(5);
        sll1.insertAtLast(9);
        sll1.insertAtLast(11);

        MergeSinglyLinkedList sll2 = new MergeSinglyLinkedList();
        sll2.insertAtLast(2);
        sll2.insertAtLast(3);
        sll2.insertAtLast(7);
        sll2.insertAtLast(10);
        sll2.insertAtLast(11);
        sll2.insertAtLast(13);
        sll2.insertAtLast(19);
        sll2.insertAtLast(20);
        
        sll1.display();
        sll2.display();
    }

    public void insertAtLast(int value){
        ListNode newNode = new ListNode(value);
        if(head==null){
            head=newNode;
            return;
        }
        ListNode current = head;
        while (null!=current.next){
            current= current.next;
        }
        current.next=newNode;
    }

    public void display(){
        ListNode current=head;
        int count=0;
        while (current!=null){
            System.out.print(current.data+"-->");
            count++;
            current=current.next;
        }
        System.out.println("null");
    }
}

我尝试过的修改

我曾新增一个display1方法,代码如下:

public void display(){
    ListNode current=head;
    int count=0;
    while (current!=null){
        System.out.print(current.data+"-->");
        count++;
        current=current.next;
    }
    System.out.println("null");
}

public void display1(){
    ListNode current=head;
    int count=0;
    while (current!=null){
        System.out.print(current.data+"-->");
        count++;
        current=current.next;
    }
    System.out.println("null");
}

调用sll1.display();和sll2.display1();,但输出没有变化。

期望输出

1-->5-->9-->11-->null
2-->3-->7-->10-->11-->13-->19-->20-->null

实际输出

1-->5-->9-->11-->2-->3-->7-->10-->11-->13-->19-->20-->null
1-->5-->9-->11-->2-->3-->7-->10-->11-->13-->19-->20-->null

问题原因与解决方案

问题根源

你把head变量声明为static了,静态变量属于类本身,不属于任何实例。所以不管创建多少个MergeSinglyLinkedList对象,它们都会共享同一个head节点。当你给sll2插入节点时,实际上是在sll1的链表末尾继续添加,最终两个实例指向的是同一个链表。

解决方法

去掉head的static修饰符,让每个实例拥有自己的头节点:

private ListNode head; // 移除static关键字

修改后,每个MergeSinglyLinkedList实例都会维护独立的链表,插入和输出就能得到预期的结果了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:02:06