I am trying to understand a java implementation for doubly linked list. I have the following code:
public class DLLNode{
//define variables
public int info;
public DLLNode next;
public DLLNode prev;
//Passing constructors
public DLLNode(int i){
info = i;
next = prev = null;
}
public DLLNode(int i, DLLNode n, DLLNode p){
info = i;
next = n;
prev = p;
}
}
And the following:
public class DLL {
DLLNode head;
DLLNode tail;
public DLL(){
head = tail = null;
}
//Check whether list is empty or not
public boolean isEmpty(){
return head == null;
}
//Insert element to head
public void insertHead(int n){
if(isEmpty()){
head = tail = new DLLNode(n);
}
else{
head = new DLLNode(n, null, head);
head.next.prev = head;
}
}
Only the insertHead() method is show here for clarity.
Now I understand that if someone runs insertHead(10) in the main method, if the list is empty; a new object forms and both head and tail reference variables points to that object.
What I don't understand is if list is NOT empty; the code piece is very confusing.
head = new DLLNode(n, null, head);
head.next.prev = head; //really confusing, what does this mean??
1)What I understand is n=10, null and head are passed to constructor: public DLLNode(int i, DLLNode n, DLLNode p).Then the assignment info=10, next=null and prev=head occurs. One problem is that, if at least one item is available on the list, and I add another item to HEAD position, shouldn't "next" point to the previous head, while "prev" point to null?? Faulty code perhaps??
2)What does the code
head.next.prev = head;
mean?? And why is it necessary?? I really don't get that logic...:(
Any help would be appreciated..
new DLLNode(n, head, null)instead. Did you try to run it?nullin the second parameter and the head in the third parameter. The second parameter goes to thenext- sonextbecomesnull, and the third parameter goes to theprev, which will become the old head. Sincenextis null,head.next.prevwill throw an NPE.