Java 无法从尾部到头部正确显示列表的节点
我的插入方法说明: 我分配了tail的“next变量”来保存旧节点的地址。我将新节点插入到列表中,并将其分配给尾部Java 无法从尾部到头部正确显示列表的节点,java,linked-list,singly-linked-list,Java,Linked List,Singly Linked List,我的插入方法说明: 我分配了tail的“next变量”来保存旧节点的地址。我将新节点插入到列表中,并将其分配给尾部 public static void main(String[] args) { LinkedList list = new LinkedList(); list.insert("A"); list.insert("B"); list.insert("C"); list.display();
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;
}
}
我试着从尾部开始显示列表,然后遍历列表,直到列表到达头部
问题:
但是输入显示的是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;
}
}
您已经创建了一个单链接列表。该列表有头和尾,链接从头到尾。设计的单链表有一个“前进”方向。通过元素[a,b,c],列表链接到a->b->c。要按相反顺序打印元素,至少有两个选项。使用递归打印元素c、b、a或实现a是否应该是tail.next=link,tail=tail.next?您使用的方式是tail.next=tail,它将指向同一个注释并创建一个循环。我测试了您的代码,但链接列表仍然显示“C”。在“display”中,您是否迭代列表中的项目?看起来你只是在打印尾巴。链接列表中的第一个节点是head。它看起来确实像是在打印tail。但是在insert中,我有tail.next=tail,它将节点连接在一起。在将新节点添加到列表中之前,我将使用对该节点的下一个变量hold引用。节点的下一个变量的作业不是包含旧节点吗?tail.next=tail链接它们吗?这不是链接到自身的同一个对象吗?您可以将您的结构更改为“反向”,并具有尾到头的方向,但不建议使用帽子-这与纹理相反,预期的行为是头到尾。因此,单链接列表只能从“头到尾”遍历。但双链接可以从“头到尾”和“尾到头”进行遍历。