rajeevbk
rajeevbk

Reputation: 87

Java LinkedList implementation insert method 0th index insertion handling

I have implemented the following java implementation of a linked list

    public class LinkedListFromScratch {
    private Node head;
    private static int size;

    public LinkedListFromScratch() {
        this.head = null;
        this.size = 0;
    }

    public boolean isEmpty() {
        return head == null;
    }

    public static int getSize() {return size;}
    

    void addToTail(int data) {
    Node newNode = new Node(data);
    //if list is empty, make new node the head.
    if (isEmpty()) {
        this.head = newNode;
        size++;
        return;
    }

    Node itterHead = head;
    while (itterHead.next != null) {
        itterHead = itterHead.next;
    }

    itterHead.next = newNode;
    size++;

}
  

    void addAtIndex(int index, int data) {

        if(index < 0 || index > this.size )
            throw new IllegalArgumentException("Index you entered is out of bounds");

        Node newNode = new Node (data);

        if(isEmpty()) {
            this.head = newNode;
            size++;
            return;
        }


      //locate the obj at index and one before it
      //newnode.next = obj
      //prevnode.next = newnode

      Node current = this.head;
      Node previous = null;
        for ( int i = 0; i < index; i++){
            previous = current;
            current = current.next;
        }


        previous.next = newNode;
        newNode.next = current;
        size++;
    }

    void printList() {
        if (isEmpty())
            System.out.print("[]");

        Node itterHead = this.head;
        System.out.print("[ ");
        while (itterHead != null) {
            System.out.print(itterHead.d + " ");
            itterHead = itterHead.next;
        }
        System.out.print("]");
        System.out.println();

    }

    class Node {
        int d;
        Node next;

        Node(int d) {
            this.d = d;
            this.next = null;
        }
    }
}

The issue here is with the addAtIndex (int index, int data) method. When I try to insert a value at index zero, it throws a null pointer exception. It makes sense because the for loop never gets executed and "previous" will always be null in the index = 0 scenario. The insertion works fine for index > 0. what is the best way to handle this case?

Upvotes: 0

Views: 48

Answers (1)

Mohsen
Mohsen

Reputation: 332

you need to check if the index is zero, this means you have new head to the list

add this code before the for-loop

if (index == 0){
    newNode.next = head;
    head = newNode;
    size++;
    return;
}

Upvotes: 1

Related Questions