Java-Doubly Linked List Logic

I am trying to understand the Java implementation for a 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;
        }
    }

For clarity, only the insertHead () method is shown here.

Now I understand that if someone runs inserthead (10) in the main method, if the list is empty; a new object is being formed, and how the reference variables of the head and tail point to this object.

I do not understand if the list is NOT empty; The code snippet is very confusing.

head = new DLLNode(n, null, head);
head.next.prev = head; //really confusing, what does this mean??

1) , n = 10, null head : public DLLNode (int i, DLLNode n, DLLNode p). = 10, next = null prev = head. , , , HEAD, "" , "prev" null? , ,

2)

head.next.prev = head;

?? ? ...: (

.

+4
2

. insertHead NullPointerException, :

 head = new DLLNode(n, null, head);
 head.next.prev = head;  // head.next is null because of the above call

:

public void insertHead(int n) {
    if (isEmpty()) {
        head = tail = new DLLNode(n);
    } else {
        head = new DLLNode(n, head, null);
        head.next.prev = head;
    }
}

node - :

  • node, next, .
  • . , head.next.prev = head.
+5

, , , ( ), , , :

(head.next).prev = head;

node, , node. , , , ,

head = new DLLNode(n, null, head);

, null, - , null.

( ).

public DLLNode(int i, DLLNode p, DLLNode n) {

.

+1

All Articles