我的插入方法说明: 我分配了尾部的“下一个变量”来保存旧节点的地址。我将尾部插入新列表中。无法正确显示列表中的节点从尾部到头部正确
我试图显示列表从尾部开始,并通过列表,直到它到达头部。
问题: 但输入显示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