Insert value in sorted way in a sorted doubly linked list
Last Updated : 4 Sep, 2024
Given a Sorted Doubly Linked Listin (non-decreasing order) and an element x, the task is to insert the element x into the correct position in the Sorted Doubly Linked List.
Example:
Input: LinkedList = 3<->5<->8<->10<->12 , x = 9 Output: 3<->5<->8<->9<->10<->12
To insert a value into a sorted doubly linked list while maintaining sorted order, start by creating a new node with the given value.
If the list is empty, new node becomes the head of the doubly linked list.
else If the new node's value is smaller than or equal to the head's value, insert it at the beginning.
else, traverse the list to find the correct position where the new nodeβs value is greater than the current node and smaller than the next node. Adjust pointers to insert the node between the current and next node or after the current node (if curr's next is NULL) .
Output
3 5 8 9 10 12
Time Complexity: O(n) , where n is the number of nodes in the linked lsit. Auxiliary Space: O(1)