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

Java链表输出与输入数量不匹配问题排查求助

问题排查与修复

问题根源

你的display方法中循环条件错误,导致最后一个节点始终无法被输出:
原代码的循环判断是while(n.next!=null),当遍历到链表最后一个节点时,n.next为null,循环会直接终止,不会执行该节点的打印操作。这正好对应你遇到的所有异常情况:

  • 插入1个值时,n.next本身就是null,循环完全不执行,无输出
  • 插入2个值时,仅第一个节点满足n.next!=null,第二个节点被跳过
  • 插入4个值时,最后一个节点(50)因n.next为null无法进入循环打印

修复方案

将display方法的循环条件从n.next!=null改为n != null,确保遍历到每一个节点。同时可以优化打印格式,避免末尾多出空格:

修改后的完整代码

import java.lang.*;
public class Main{
    Node head;
    static class Node{
        int data;
        Node next;
        public Node(int d){
            data=d;
            next=null;
        }
    }

    public void insertFirst(int data)
    {
        Node n=new Node(data);
        n.next=head;
        head=n;
    }

    public void insertLast(int data){
        Node n=new Node(data);
        if(head==null) {
            head = n;
        } else{
            Node t=head;
            while(t.next!=null)
            {   t=t.next;}
               t.next=n;
        }
    }

    public void display(){
        Node n=head;
        if(n==null)
            System.out.println("empty");
        else
        {
            // 修改循环条件为n != null,遍历所有节点
            while(n != null)
            {
                System.out.print(n.data);
                // 仅在非最后一个节点后添加空格
                if(n.next != null){
                    System.out.print(" ");
                }
                n=n.next;
            }
            System.out.println();
        }
    }

    public static void main(String [] args){
        Main m=new Main();
        m.insertFirst(34);
        m.insertFirst(4);
        m.insertLast(5);
        m.insertLast(50);
        m.display();
    }
}

验证结果

修改后运行代码,输出为4 34 5 50,完全符合预期;插入单个值时会正常打印该值,插入两个值时两个节点都会被显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:50:24