Skip to content

Instantly share code, notes, and snippets.

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/fc0d0fc2171ed891330d5cf773c45206 to your computer and use it in GitHub Desktop.
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.
/*
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