Created
May 9, 2016 20:54
-
-
Save jianminchen/5b357be38d6bad427e885c7b7343c19b to your computer and use it in GitHub Desktop.
HackerRank - LinkedList - Insert a node at a specific position
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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