我的插入方法說明: 我分配了尾部的「下一個變量」來保存舊節點的地址。我將尾部插入新列表中。無法正確顯示列表中的節點從尾部到頭部正確
我試圖顯示列表從尾部開始,並通過列表,直到它到達頭部。
問題: 但輸入顯示C這不是我想要的。顯示方法應該顯示C,B,A。
我甚至在紙上調試我的代碼。我不知道爲什麼顯示不檢索鏈接列表中鏈接節點的最後一個地址。它只檢索列表中的最後一個節點,並只顯示列表中的最後一個節點。
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.insert("A");
list.insert("B");
list.insert("C");
list.display();
}
public void insert(String data)
{
Link link = new Link(data);
// this code only executes the first time when the list has
// no node
if(head == null)
{
head = link;
tail= link;
}
// this code will execute when the linked list has one or more node
else
{
tail.next = tail;
tail = link;
}
}
public void display()
{
while(tail != null)
{
System.out.println(tail.data);
tail = tail.next;
}
}
不應該是tail.next = link,tail = tail.next?你擁有它的方式是tail.next = tail,它將指向相同的音符並創建一個循環。 –
我測試了您的代碼,但鏈接列表仍顯示「C.」。 「display」中的 – Nicholas
是否迭代列表中的項目?它看起來像你只是打印尾巴。鏈表中的第一個節點是頭。 – Paxic