Reputation: 11
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);
}
}
To my understanding, I must point the tail of the list to the head node when implementing a circular linked list. This is the implementation of a doubly circular linked list I have and the commented out line is what I do not understand why is causing an error. It seems like the tail is either null or getting stuck in an infinite loop, can someone help me understand please? thank you
Upvotes: 1
Views: 181
Reputation: 11
Error was with my length and toString methods small modification, thanks for help.
Upvotes: 0
Reputation: 2687
public void insertAtHead(E data)
{
Node<E> newNode=new Node<E>(data);
if(this.head==null)
{
this.head=newNode;
newNode.nextNode=this.head; // this should NOT be the bug place
newNode.prevNode=this.head; // add this
this.tail=this.head;
}
else {
newNode.prevNode = this.tail;
this.head.prevNode = newNode;
newNode.nextNode = this.head;
this.head = newNode;
tail.nextNode = this.head // add this
System.out.println("tail.next is: " + this.tail.nextNode);
}
}
Upvotes: 0