Insert value in sorted way in a sorted doubly linked list
Given a sorted doubly linked list and a value to insert, write a function to insert the value in sorted way.
Initial doubly linked list
Doubly Linked List after insertion of 9
Let input doubly linked list is sorted in increasing order. New node passed to the function contains data in the data part and previous and next link are set to NULL.
sortedInsert(head_ref, newNode) if (head_ref == NULL) head_ref = newNode else if head_ref->data >= newNode->data newNode->next = head_ref newNode->next->prev = newNode head_ref = newNode else Initialize current = head_ref while (current->next != NULL and current->next->data < newNode->data) current = current->next newNode->next = current->next if current->next != NULL newNode->next->prev = newNode current->next = newNode newNode->prev = current
Created Doubly Linked Listn3 5 8 9 10 12
Time Complexity: O(n)
Auxiliary Space: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.