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 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 List 3 5 8 9 10 12
Time Complexity: 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 contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Sorted insert in a doubly linked list with head and tail pointers
- Merge K sorted Doubly Linked List in Sorted Order
- Given a linked list which is sorted, how will you insert in sorted way
- Sorted insert for circular linked list
- Sorted merge of two sorted doubly circular linked lists
- Sort a k sorted doubly linked list
- Remove duplicates from a sorted doubly linked list
- Find pairs with given product in a sorted Doubly Linked List
- Count triplets in a sorted doubly linked list whose sum is equal to a given value x
- Count triplets in a sorted doubly linked list whose product is equal to a given value x
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Sorted Linked List to Balanced BST
- Check if a Linked List is Pairwise Sorted
- Remove duplicates from a sorted linked list
- Finding Median in a Sorted Linked List