Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 9, 2016 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/5b357be38d6bad427e885c7b7343c19b to your computer and use it in GitHub Desktop.
Save jianminchen/5b357be38d6bad427e885c7b7343c19b to your computer and use it in GitHub Desktop.
HackerRank - LinkedList - Insert a node at a specific position
/*
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
struct Node
{
int data;
struct Node *next;
}
*/
Node* InsertNth(Node *head, int data, int position)
{
Node* newHead = new Node();
newHead->data = data;
if(head==NULL)
return newHead;
if(position ==0)
{
newHead->next = head;
return newHead;
}
Node* nextHead = InsertNth(head->next, data, position -1);
head->next = nextHead;
return head;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment