2

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;

}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194

1 Answers1

0

You are not saving the head pointer and therfore you return null when you write return curr immidiately after loop with condition while (curr != null). So change your code to return the actual head of linked list.

Also once insertion is done, no need for extra traversal, so add a break statement as well:

int counter = 0;
Node head = curr;// save pointer to head of linked list.
while (curr != null) {
    if (counter+1 == position) {
    insert.next = curr.next;
    curr.next = insert;
    break;      
    }
curr = curr.next;
counter++;
}
return head;
Sumeet
  • 8,086
  • 3
  • 25
  • 45
  • Thank you so much! I always wondered about this. You create a temp variable, change that and then the head gets changed? How does that work? – Sadaf Chowdhury Jan 22 '18 at 15:01