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 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Given a linked list which is sorted, how will you insert in sorted way
- Sorted insert in a doubly linked list with head and tail pointers
- Merge K sorted Doubly Linked List in Sorted Order
- 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
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Difference between Singly linked list and Doubly linked list
- Sorted merge of two sorted doubly circular linked lists
- Construct a Doubly linked linked list from 2D Matrix
- Sorted insert for circular linked list
- Remove duplicates from a sorted doubly linked list
- Sort a k sorted doubly linked list
- Find pairs with given product in a sorted Doubly Linked List
- Delete all the nodes from the doubly linked list that are greater than a given value
- Delete all the nodes from a doubly linked list that are smaller than a given value
- Insert node into the middle of the linked list
- Insert a whole linked list into other at k-th position
- Insert a node at a specific position in a linked list
- Insert N elements in a Linked List one after other at middle position