有人可以用我寫(xiě)的代碼幫我解決這個(gè)問(wèn)題嗎?當(dāng)我運(yùn)行它時(shí),它不會(huì)打印出鏈接列表的值。我不明白問(wèn)題出在哪里,當(dāng)我運(yùn)行代碼時(shí)編譯器一直顯示空白屏幕。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 回答

狐的傳說(shuō)
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
? 你必須這樣做嗎?Java已經(jīng)有一個(gè)LinkedList
實(shí)用程序,使它更容易。

一只斗牛犬
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超2個(gè)贊
在您的 Link 類中,您需要更改以下內(nèi)容:
if (head == null)
{
node=head; //<-- change this to head = node;
}

POPMUISE
TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
您的代碼正在執(zhí)行此操作:
if (head == null)
{
node=head;
}
這會(huì)將 null in 設(shè)置head為變量node。您沒(méi)有設(shè)置head.
你應(yīng)該這樣做(設(shè)置node變量的值head):
if (head == null)
{
head = node;
}
添加回答
舉報(bào)
0/150
提交
取消