【发布时间】:2020-04-21 05:36:13
【问题描述】:
public class LinkedList<E> {
private Node<E> head;
private Node<E> tail;
/* Inserts*/
public void insertAtHead(E data)
{
Node<E> newNode=new Node<E>(data);
if(this.head==null)
{
this.head=newNode;
//newNode.nextNode=this.head; <--- Here is error cause
this.tail=this.head;
}
else {
newNode.prevNode = this.tail;
this.head.prevNode = newNode;
newNode.nextNode = this.head;
this.head = newNode;
System.out.println("tail.next is: " + this.tail.nextNode);
}
}
据我了解,在实现循环链表时,我必须将链表的尾部指向头节点。这是我拥有的双循环链表的实现,注释掉的行是我不明白为什么会导致错误的原因。看起来尾巴要么为空,要么陷入无限循环,有人可以帮我理解吗?谢谢
【问题讨论】:
-
this.tail.nextNode = newNode;我认为 else 语句中缺少。
-
我也试过了,但 tail.nextNode 仍然给我一个无限循环。
标签: java data-structures doubly-linked-list circular-list