-1

I am solving linked list question on geeksforgeeks platform and i was given a question, i will mention the link to check it. I am getting nullpointer expection for this. link:- https://practice.geeksforgeeks.org/problems/linked-list-insertion-1587115620/1/?category[]=Linked%20List&difficulty[]=-1&page=1&query=category[]Linked%20Listdifficulty[]-1page1#

Code:-

 Node insertAtBeginning(Node head, int x)
{
    // code here
    Node inserting = new Node(x);
    inserting.next = head;
    return inserting;
}

// Should insert a node at the end
Node insertAtEnd(Node head, int x)
{
    // code here
    Node first = head;
    while(head.next != null){
        head = head.next;
    }
    Node inserting = new Node(x);
    head.next = inserting;
    return first;
    
}
SUPER ADI
  • 17
  • 4
  • Please also add the exception stack trace and the main code where you call the insert functions. Maybe you can add a null check for the `head` object. If the `head` is `null` return the created `inserting` object. – Butiri Dan Dec 23 '20 at 09:01

1 Answers1

1

Regarding the problem description:

Hint: When inserting at the end, make sure that you handle NULL explicitly.

It seems if the list is not initialized and the insertAtEnd method is called, the 'head' parameter is null. That case is given by example 2 in the problem description.

I suggest to make null like check like:

Node insertAtEnd(Node head, int x){
  if(head == null){
    return new Node(x);
  }
  ...
}
CDroescher
  • 73
  • 5