Insert a node at a specific position in a linked list
The following is the solution to Hacker Rank problem Insert a node at a specific position in a linked list using Java. For solutions to other Hacker Rank Problem visit my page HackerRank, alternatively try searching for the problem in my blog.
Score: 5/5
Node* InsertNth(Node *head, int data, int position)
{
// Complete this method only
// Do not write main function.
Node *newNode = new Node();
newNode->data = data;
newNode->next = NULL;
Node *temp = head;
if(position == 0)
{
newNode->next = head;
head = newNode;
}
else
{
for(int i = 1; i < position; i++)
temp = temp->next;
newNode->next = temp->next;
temp->next = newNode;
}
return head;
}
The following is the solution to Hacker Rank problem Insert a node at a specific position in a linked list using Java. For solutions to other Hacker Rank Problem visit my page HackerRank, alternatively try searching for the problem in my blog.
Score: 5/5
Node* InsertNth(Node *head, int data, int position)
{ // Complete this method only // Do not write main function. Node *newNode = new Node(); newNode->data = data; newNode->next = NULL; Node *temp = head; if(position == 0) { newNode->next = head; head = newNode; } else { for(int i = 1; i < position; i++) temp = temp->next; newNode->next = temp->next; temp->next = newNode; } return head; } |