We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
There is a flaw in the design of the problem's INPUT/OUTPUT.
It should give head as NULL which it does not.
There is an extra number expected at the end of the linked list
This is accepted code,
Node* InsertNth(Node *head, int data, int position)
{
if (position == 0)
return head = new Node({data, new Node({2, NULL})});
Node* root = head;
while (root->next && --position)
root = root->next;
root->next = new Node({data, root->next});
return head;
}
And, this is what accepted code should look like,
Node* InsertNth(Node *head, int data, int position)
{
if (head == NULL)
return head = new Node({data, NULL});
if (position == 0)
return head = new Node({data, head->next});
// strict checking as my habit
if (position < 0)
return NULL;
Node* root = head;
while (root->next && --position)
root = root->next;
root->next = new Node({data, root->next});
return head;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Insert a node at a specific position in a linked list
You are viewing a single comment's thread. Return to all comments →
There is a flaw in the design of the problem's INPUT/OUTPUT.
This is accepted code,
And, this is what accepted code should look like,