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 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 email@example.com. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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 merge of two sorted doubly circular linked lists
- Sorted insert for circular linked list
- Sort a k sorted doubly linked list
- Remove duplicates from a sorted doubly linked list
- Count triplets in a sorted doubly linked list whose sum is equal to a given value x
- Find pairs with given product in a sorted Doubly Linked List
- 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
- Merge two sorted linked list without duplicates
- Check if a Linked List is Pairwise Sorted
- Remove duplicates from a sorted linked list
- Finding Median in a Sorted Linked List
- Merge two unsorted linked lists to get a sorted list
- Remove all occurrences of duplicates from a sorted Linked List
- Check if linked list is sorted (Iterative and Recursive)
- Sort linked list which is already sorted on absolute values