I'm doing a codefights linkedlist question and I just can't seem to understand why my code is throwing a NullPointerException.
The way I wrote it was that once you hit a position like the third index, it would make the insert's next be the current node's next and then making the new current's next be the insert so that we can insert the node in. I did counter+1 to avoid Null issues but it looks like I failed :/
/*
  Insert Node at a given position in a linked list 
  head can be NULL 
  First element in the linked list is at position 0
  Node is defined as 
  class Node {
    int data;
     Node next;
  }
*/
Node InsertNth(Node head, int data, int position) {
   // This is a "method-only" submission. 
    // You only need to complete this method. 
    Node curr = head;
    Node insert = new Node();
    insert.data = data;
    insert.next = null;
    if (curr == null)
        return insert;
    if (position == 0) {
        insert.next = curr;
        return insert;
    }
    int counter = 0;
    while (curr != null) {
        if (counter+1 == position) {
        insert.next = curr.next;
        curr.next = insert;      
        }
    curr = curr.next;
    counter++;
    }
    return curr;
}
 
     
    