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/e1e528eda506c185182a68a0df3be544 to your computer and use it in GitHub Desktop.
Save jianminchen/e1e528eda506c185182a68a0df3be544 to your computer and use it in GitHub Desktop.
Better solution - using recursive solution, short, less code to write.
/*
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)
{
// Complete this function
// Do not write the main method.
if(head==NULL)
{
head=(Node*)malloc(sizeof(Node));
head->data=data;
head->next=NULL;
return head;
}
else if(data <= head->data)
{
Node* temp=(Node*)malloc(sizeof(Node));
temp->data=data;
temp->next=head;
head->prev=temp;
return temp;
}
else
{
head->next=SortedInsert(head->next, data);
(head->next)->prev=head;
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment