Search code examples
javanodes

Insert Nodes in the Linked List


I have an insert method that inserts a node into a linked list. The problem is, every time a node is added, the recent node added becomes the head node and loses the nodes before it. How do I keep the head node value and link it to the next nodes that will be added?

Here's the code

    private Node<D> startOfNode;
    private Node<D> endOfNode;  

    public void insert(D data) throws ListOverflowException {
    Node<D> head = new Node<>(data);
    startOfNode = head;

    if (head.getData() != null) {
        Node<D> node1 = new Node<>(data);
        head.setNext(node1);
        endOfNode = node1;
    }
}

I use this print method:

public void printList() {
    Node<D> curr = startOfNode;
    int counter = 0;

    while(curr!=null) {
        System.out.println("Item " + counter + " :" + curr.getData());
        curr = curr.getNext();
        counter++;
    }
    System.out.println("Item " + counter + " :" + null);
}

Both of these methods belong to the same class. I use a tester class and instantiate the said class.

When I try to to add two nodes with values of 20 and 30, I get this result:
Item 0 :30
Item 1 :30

But it's supposed to be:
Item 0 :20
Item 1 :30


Solution

  • You are resetting the head everytime you add a data in your insert method.

    You can iterate from the startnode and when you find the next node is null, you can add a new node and attach it to the current node's next and just update the endNode.

    Or you can go to the endnode and attach a new node with the passed value.

    A simple way of doing it is shown below:

    private Node head;
    private Node tail; 
    
    public void insert(int data){
        Node newNode = new Node(data); //Create
            
        if(tail != null) { //Link
            tail.next = newNode;
        }       
            
        if(head == null) {  //Update head.
            head = newNode;
        }
            
        tail = newNode;  //Update tail.
    }