Created
May 8, 2016 23:35
-
-
Save jianminchen/fc0d0fc2171ed891330d5cf773c45206 to your computer and use it in GitHub Desktop.
HackerRank - insert a node in double linked list - use recursive function, less code to write, shorten the time to complete the task.
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 in a doubly sorted linked list | |
After each insertion, the list should be sorted | |
Node is defined as | |
struct Node | |
{ | |
int data; | |
Node *next; | |
Node *prev; | |
} | |
*/ | |
Node* SortedInsert(Node *head,int data) | |
{ | |
if(head ==NULL) | |
{ | |
Node* newHead = new Node(); | |
newHead->data = data; | |
return newHead; | |
} | |
if(data < head->data) | |
{ | |
Node* newHead = new Node(); | |
newHead->data = data; | |
newHead->next = head; | |
head->prev = newHead; | |
return newHead; | |
} | |
head->next = SortedInsert(head->next, data); | |
return head; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment