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

Java实现单向链表时尾节点数据丢失问题求助

问题解答

大家好,感谢各位的评论。问题已解决,我还学到了一些编辑和格式设置的新技巧。我想给每条评论点赞并关闭帖子,但还没弄明白操作方法,之后再处理。

原始问题

在main方法中编写代码时,我无法打印出单向链表尾节点的数据。注释掉display方法就能看到我的原始代码。只有使用main方法外的display方法时,我才能打印出所有数据。请解释为何display方法可行,而另一种方式不行。

代码示例

package learnSingleLinkedList;

public class SinglyLinkedList {
    private ListNode head;
    private static class ListNode
    {
        private int data;
        private ListNode next;
        
        ListNode(int data)
        {
            this.data = data;
            this.next = null;
        }
    }
public void display()
    {
        ListNode current = head;
        while(current!=null)
        {
            System.out.print(current.data+" --> ");
            current = current.next;
        }
        System.out.print("Null");
    }
    public static void main(String[] args)
    {
        SinglyLinkedList sll = new SinglyLinkedList();
        sll.head = new ListNode(10);
        ListNode second = new ListNode(1);
        ListNode third = new ListNode(8);
        ListNode fourth = new ListNode(11);
        
        sll.head.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = null;
        
        ListNode current = sll.head;
        while(current.next != null)
        {
            System.out.println(current.data);
            current = current.next;
        }
        
        sll.display();
    }
}

原因分析

核心差异在两个循环的终止条件:

  • main方法里的循环:用的是while(current.next != null)。当current走到尾节点(值为11的节点)时,current.next是null,循环直接终止,不会执行打印这个尾节点的操作。
  • display方法里的循环:用的是while(current != null)。只要current不是null就会执行打印,打印完再把current指向next。直到current变成null(尾节点的下一个位置)才停止,所以尾节点的data会被正常打印出来。

如果要让main里的代码也能打印尾节点,要么把循环条件改成current != null,要么在循环结束后单独打印一次current.data(此时current正好指向尾节点)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 03:48:35