VOOZH about

URL: https://www.geeksforgeeks.org/dsa/insert-value-sorted-way-sorted-doubly-linked-list/

⇱ Insert value in sorted way in a sorted doubly linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Insert value in sorted way in a sorted doubly linked list

Last Updated : 4 Sep, 2024

Given a Sorted Doubly Linked List in (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

πŸ‘ Insert-in-Sorted-way-in-a-Sorted-DLL-2

Explanation: Here node 9 is inserted between 8 and 10 in the Doubly Linked-List.


Input: LinkedList = 1<->4<->10<->11 , x = 15
Output: 1<->4<->10<->11<->15

πŸ‘ Insert-in-Sorted-way-in-a-Sorted-DLL-4

Explanation: Here node 15 is inserted at end in the Doubly Linked-List.

Approach:

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)

Comment
Article Tags: