Initialize a Linked List

Let see how to initialize a LinkedList. Here we will be initializing a Integer Linked list storing int value as datatype.
LinkedList is a class representing the list, LinkedNode is represented as a separate class. If you are unaware of the terms, please refer to our previous tutorial introduction to linked list.

class LinkedNode {
    protected int value;
    protected LinkedNode next;
    public LinkedNode(int value) {
        this.value = value;
        this.next = null;
    } 
}

public class LinkedList {

    static LinkedNode head =  null;
    public static void main(String[] args) {
 System.out.println("Initialize a LinkedList");
        LinkedList linkedList = new LinkedList();
        LinkedNode node = new LinkedNode(1);
 LinkedList linkedList = new LinkedList();
        LinkedNode node = new LinkedNode(1);
        linkedList.addNode(node);
        LinkedNode node2 = new LinkedNode(2);
        linkedList.addNode(node2);
        LinkedNode node3 = new LinkedNode(3);
        linkedList.addNode(node3);
        System.out.println("After adding nodes, the list is -");
        linkedList.printList();
        linkedList.deleteNode(new LinkedNode(2));
        System.out.println("After deleting node 2 if present, the list is -");
        linkedList.printList();
 }
}
Here LinkedNode is the node for the Linked List to be created. It contains int as data and a next link which is of datatype LinkedNode to link to the next node of the list.

 LinkedList is the list class we are interested to create. It has a static variable head initialize to null which always points to the head node of the list. We initialize the list in the line LinkedList linkedList = new LinkedList();  and initialize a node in LinkedNode node = new LinkedNode(1); We will explain why head is made as a static variable in next tutorials.
LinkedList class have functions of adding a node to the list, deleting a node from the list and printing the list. We will explain all these methods in our next tutorials.

That's all of initializing a LinkedList. Hope you like it. Please comments for any doubts.

Happy Learning !!!

SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment