为了账号安全,请及时绑定邮箱和手机立即绑定

如何打印出链表?

如何打印出链表?

小唯快跑啊 2022-10-07 17:45:49
有人可以用我写的代码帮我解决这个问题吗?当我运行它时,它不会打印出链接列表的值。我不明白问题出在哪里,当我运行代码时编译器一直显示空白屏幕。public class Node {    int data;    Node next;    public static void main (String Args [])    {        Link object = new Link ();        object.insert(15);        object.insert(30);        object.insert(50);        object.insert(70);        object.show();    }}public class Link {    Node head;    void insert (int data)    {        Node node = new Node();        node.data=data;        if (head == null)        {            node=head;        }        else        {            Node n = head;            while (n.next != null)            {                n=n.next;            }            n.next=node;        }    }    void show ()    {        Node n = head;        while (n != null)        {            System.out.println(n.data);            n=n.next;        }    }}
查看完整描述

3 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

¿ 你必须这样做吗?Java已经有一个LinkedList实用程序,使它更容易。



查看完整回答
反对 回复 2022-10-07
?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

在您的 Link 类中,您需要更改以下内容:


if (head == null)

{

    node=head; //<-- change this to   head = node;

}


查看完整回答
反对 回复 2022-10-07
?
POPMUISE

TA贡献1765条经验 获得超5个赞

您的代码正在执行此操作:


if (head == null)

{

    node=head;

}

这会将 null in 设置head为变量node。您没有设置head.


你应该这样做(设置node变量的值head):


if (head == null)

{

    head = node;

}


查看完整回答
反对 回复 2022-10-07
  • 3 回答
  • 0 关注
  • 93 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信