RanjanaLK RanjanaLK - 3 months ago 10
Java Question

How a java class works with it's own reference type

I'm fairly new to JAVA and OOP and I'm currently following an academic course where I'm learning data structures and algorithms in java.

As I was learning about implementation of linked lists I've ran into a small problem of not understanding the code how to create a node when implementing a linked list(I'm familiar with constructors and bit of recursion ).

Code of the Node class as follows

public class Node {
public int info;
public Node next, prev;
public Node (int el) {
this (el,null,null);
}
public Node (int el,Node n,Node p){
info = el; next =n; prev=p;
}
}


I need to know what's happening behind the scene when the code executes(especially how the line3 works)and code of the List class is as follows

public class List {
private Node head, tail;
public List ( ){
head = tail = null;
}
public boolean isEmpty( ){
return head == null;
}
public void addToTail (int el) {
if (!isEmpty ( )) {
tail = new Node (el, null, tail);
tail.prev.next = tail;
}
else head = tail = new Node(el);
}
public int removeFromTail ( ){
int el = tail.info;
if (head == tail)
head = tail =null;
else
{
tail = tail.prev; tail.next = null;
}
return el;
}
}


(This example is given by the academy where I'm learning and I want to know how it works)

Please explain how the Node class works.

Answer

Ok let's start from the Node Class

public Node next, prev;
    public Node (int el) {
        this (el,null,null);
    }

Here the objects next and prev are references to the next and previous nodes to the current node (which is your current object (this))

this (el,null,null);

It means you are creating a node which has no previous or next node. as you pass null, null for next and previous. Its similar to creating a head as head doesn't have next and previous nodes.

When you create the head you will never change it but you will change the next of the head the time when you create the second element in your list

When you create a tail of the linked list

 public void addToTail (int el) {
        if (!isEmpty ( )) {
        tail = new Node (el, null, tail);
        tail.prev.next = tail;
        } 
        else head = tail = new Node(el);
    }

here you first create a tail Node by tail = new Node (el, null, tail); And then get the previous of tail and set the next element of the prev as the tail by doing tail.prev.next = tail;

Every time you add a new Node to the list you are calling addToTail(int e1) which updates the tail and updates the next of the old tail.