Search code examples
javaooplinked-listnodes

Why is new Node is not added?


public class LinkedList {


    static Node head;

    static class Node{
        int data;
        Node next;

        Node(int dat){
            data = dat;
            next = null;
        }

    }

    public void add(int data){
        Node node = new Node(data);
        Node n = head;
        while (n!= null){
            n = n.next;
        }
        n = node;

    }

    public void print(){
        Node n = head;

        while(n!=null){
            System.out.println(n.data);
            n = n.next;
        }
    }
}

I realize that in the add() method I am assigning 'node' to an item that has the value null, however, the doubt is even is n.next becomes null its still a node right because 'next' is defined as a Node, so it should work right.


Solution

  • To add the new node at the end of the linked list, you need to take following steps:

    1. Create the new node
    2. Check if linked list is empty. If it is, point the head to the new node and return from the function
    3. If linked list is not empty, traverse the linked list until the last node is reached
    4. Point the next of the last node to the new node created in step 1.

    Problem

    There are couple of problems in your code:

    1. You are not handling the special case of adding the new node in the empty linked list
    2. while loop in the add() method doesn't stops when the last node is reached. It only stops when n itself becomes null which means you cannot add the new node in the linked list

    Solution

    You need to change the condition in the while loop from

    n != null
    

    to

    n.next != null
    

    to make sure that you are at the last node in the linked list after the loop ends and then to add the new node in the linked list, you need to point the next of the last node to the new node

    n.next = node;
    

    Your add() method should be written as:

    public void add(int data) {
        Node node = new Node(data);
    
        if (head == null) {
           head = node;
           return;
        }
    
        Node n = head;
    
        while (n.next != null){
            n = n.next;
        }
    
        n.next = node;
    }