Java 如何打印linkedlist?
有人能用我写的代码帮我解决这个问题吗 当我运行时,它不会打印出链表的值。我不明白是什么问题,当我运行代码时,编译器一直给我一个空白屏幕Java 如何打印linkedlist?,java,linked-list,Java,Linked List,有人能用我写的代码帮我解决这个问题吗 当我运行时,它不会打印出链表的值。我不明白是什么问题,当我运行代码时,编译器一直给我一个空白屏幕 public class Node { int data; Node next; public static void main (String Args []) { Link object = new Link (); object.insert(15); object.ins
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;
}
}
}
您的代码正在执行以下操作:
if (head == null)
{
node=head;
}
这将head
中的null设置为变量节点
。您没有设置head
的值
您应该这样做(将节点
的值设置为变量头
):
在链接类中,您需要更改以下内容:
if (head == null)
{
node=head; //<-- change this to head = node;
}
if(head==null)
{
No.= Head;//< p>你必须这样做吗?java已经有了<代码>链接目录> /Cuff>实用程序,使它更容易。< / P>是的,我知道有一个内置的库,但是,既然我是初学者,我想我应该知道如何从头开始构建数据结构。@ JCM如果这个答案解决了你的问题,那么请考虑接受它,单击左侧的绿色复选标记。
if (head == null)
{
node=head; //<-- change this to head = node;
}