Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Insert a Node after a given node in Doubly Linked List
Next article icon

Insert value in sorted way in a sorted doubly linked list

Last Updated : 04 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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) .
C++
// C++ implementation to insert value in sorted way // in a sorted doubly linked list #include <iostream> using namespace std;  class Node { public:     int data;     Node* prev;     Node* next;        Node(int new_data) {         data = new_data;         prev = nullptr;         next = nullptr;     } };  // Function to insert element x into sorted DLL Node* sortedInsert(Node* head, int x) {        // Create a new node with the given data     Node* newNode = new Node(x);      // If the list is empty, set new node as the head     if (head == nullptr) {         return newNode;     }      // If new node needs to be inserted at beginning     if (x <= head->data) {         newNode->next = head;         head->prev = newNode;         return newNode;     }      // Traverse the list to find correct position     Node* curr = head;     while (curr->next != nullptr && curr->next->data < x) {         curr = curr->next;     }      // Insert the new node in the correct position     newNode->next = curr->next;     if (curr->next != nullptr) {         curr->next->prev = newNode;     }     curr->next = newNode;     newNode->prev = curr;      return head; }  void printList(Node* curr) {     while (curr != nullptr) {         cout << curr->data << " ";         curr = curr->next;     } }  int main() {        // Create hardcoded DLL:   	 // 3 <-> 5 <-> 8 <-> 10 <-> 12     Node* head = new Node(3);     head->next = new Node(5);     head->next->prev = head;     head->next->next = new Node(8);     head->next->next->prev = head->next;     head->next->next->next = new Node(10);     head->next->next->next->prev = head->next->next;     head->next->next->next->next = new Node(12);     head->next->next->next->next->prev =          head->next->next->next;      int x = 9;     head = sortedInsert(head, x);     printList(head);     return 0; } 
C
// C implementation to insert value in sorted way // in a sorted doubly linked list #include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node *prev, *next; };  struct Node *createNode(int data);  // Function to insert an element x into the correct // position in a sorted doubly linked list struct Node *sortedInsert(struct Node *head, int x) {      // Create a new node with the given data     struct Node *newNode = createNode(x);      // If the list is empty, return the new node     // as the head     if (head == NULL) {         return newNode;     }      // If the new node needs to be inserted at the     // beginning     if (x <= head->data) {         newNode->next = head;         head->prev = newNode;         return newNode;     }      // Traverse the list to find the correct position     // to insert the new node     struct Node *curr = head;     while (curr->next != NULL && curr->next->data < x) {         curr = curr->next;     }      // Insert the new node in the    	// correct position     newNode->next = curr->next;     if (curr->next != NULL) {         curr->next->prev = newNode;     }     curr->next = newNode;     newNode->prev = curr;      return head; }  void printList(struct Node *curr) {     while (curr != NULL) {         printf("%d ", curr->data);         curr = curr->next;     } }  struct Node *createNode(int data) {     struct Node *newNode =        (struct Node *)malloc(sizeof(struct Node));     newNode->data = data;     newNode->prev = newNode->next = NULL;     return newNode; }  int main() {      // Create a hardcoded doubly linked list:     // 3 <-> 5 <-> 8 <-> 10 <-> 12     struct Node *head = createNode(3);     head->next = createNode(5);     head->next->prev = head;     head->next->next = createNode(8);     head->next->next->prev = head->next;     head->next->next->next = createNode(10);     head->next->next->next->prev = head->next->next;     head->next->next->next->next = createNode(12);     head->next->next->next->next->prev = head->next->next->next;      int x = 9;     head = sortedInsert(head, x);     printList(head);      return 0; } 
Java
// Java implementation to insert value in sorted way // in a sorted doubly linked list class Node {     int data;     Node prev, next;      Node(int data) {         this.data = data;         this.prev = null;         this.next = null;     } }  public class GfG {      // Function to insert an element x into the     // correct position in a sorted doubly linked list     static Node sortedInsert(Node head, int x) {                // Create a new node with the given data         Node newNode = new Node(x);          // If the list is empty, return the new node         // as the head         if (head == null) {             return newNode;         }          // If the new node needs to be inserted at         // the beginning         if (x <= head.data) {             newNode.next = head;             head.prev = newNode;             return newNode;         }          // Traverse the list to find the correct         // position to insert the new node         Node curr = head;         while (curr.next != null && curr.next.data < x) {             curr = curr.next;         }          // Insert the new node in the correct position         newNode.next = curr.next;         if (curr.next != null) {             curr.next.prev = newNode;         }         curr.next = newNode;         newNode.prev = curr;          return head;     }      static void printList(Node curr) {         while (curr != null) {             System.out.print(curr.data + " ");             curr = curr.next;         }     }      public static void main(String[] args) {          // Create a hardcoded doubly linked list:         // 3 <-> 5 <-> 8 <-> 10 <-> 12         Node head = new Node(3);         head.next = new Node(5);         head.next.prev = head;         head.next.next = new Node(8);         head.next.next.prev = head.next;         head.next.next.next = new Node(10);         head.next.next.next.prev = head.next.next;         head.next.next.next.next = new Node(12);         head.next.next.next.next.prev =                              head.next.next.next;          int x = 9;         head = sortedInsert(head, x);         printList(head);     } } 
Python
# Python implementation to insert value in sorted way # in a sorted doubly linked list  class Node:     def __init__(self, data):         self.data = data         self.prev = None         self.next = None  # Function to insert an element x into the correct # position in a sorted doubly linked list def sorted_insert(head, x):        # Create a new node with the given data     new_node = Node(x)      # If the list is empty, return the new node     # as the head     if head is None:         return new_node      # If the new node needs to be inserted at     # the beginning     if x <= head.data:         new_node.next = head         head.prev = new_node         return new_node      # Traverse the list to find the correct     # position to insert the new node     curr = head     while curr.next is not None and curr.next.data < x:         curr = curr.next      # Insert the new node in the correct position     new_node.next = curr.next     if curr.next is not None:         curr.next.prev = new_node     curr.next = new_node     new_node.prev = curr      return head  def print_list(curr):     while curr is not None:         print(curr.data, end=" ")         curr = curr.next     print()  if __name__ == "__main__":      # Create a hardcoded doubly linked list:     # 3 <-> 5 <-> 8 <-> 10 <-> 12     head = Node(3)     head.next = Node(5)     head.next.prev = head     head.next.next = Node(8)     head.next.next.prev = head.next     head.next.next.next = Node(10)     head.next.next.next.prev = head.next.next     head.next.next.next.next = Node(12)     head.next.next.next.next.prev = head.next.next.next      x = 9     head = sorted_insert(head, x)     print_list(head) 
C#
// C# implementation to insert value in sorted way // in a sorted doubly linked list using System;  class Node {     public int data;     public Node prev, next;      public Node(int data) {         this.data = data;         this.prev = null;         this.next = null;     } }  class GfG {      // Function to insert an element x into the     // correct position in a sorted doubly linked list     static Node SortedInsert(Node head, int x) {                // Create a new node with the given data         Node newNode = new Node(x);          // If the list is empty, return the new node         // as the head         if (head == null) {             return newNode;         }          // If the new node needs to be inserted at         // the beginning         if (x <= head.data) {             newNode.next = head;             head.prev = newNode;             return newNode;         }          // Traverse the list to find the correct         // position to insert the new node         Node curr = head;         while (curr.next != null && curr.next.data < x) {             curr = curr.next;         }          // Insert the new node in the correct position         newNode.next = curr.next;         if (curr.next != null) {             curr.next.prev = newNode;         }         curr.next = newNode;         newNode.prev = curr;          return head;     }      static void PrintList(Node curr) {         while (curr != null) {             Console.Write(curr.data + " ");             curr = curr.next;         }         Console.WriteLine();     }      static void Main() {          // Create a hardcoded doubly linked list:         // 3 <-> 5 <-> 8 <-> 10 <-> 12         Node head = new Node(3);         head.next = new Node(5);         head.next.prev = head;         head.next.next = new Node(8);         head.next.next.prev = head.next;         head.next.next.next = new Node(10);         head.next.next.next.prev = head.next.next;         head.next.next.next.next = new Node(12);         head.next.next.next.next.prev = head.next.next.next;          int x = 9;         head = SortedInsert(head, x);         PrintList(head);     } } 
JavaScript
// JavaScript implementation to insert value // in sorted way in a sorted doubly linked list  class Node {     constructor(data) {         this.data = data;         this.prev = null;         this.next = null;     } }  // Function to insert an element x into the correct // position in a sorted doubly linked list function sortedInsert(head, x) {      // Create a new node with the given data     const newNode = new Node(x);      // If the list is empty, return the new node     // as the head     if (head === null) {         return newNode;     }      // If the new node needs to be inserted at     // the beginning     if (x <= head.data) {         newNode.next = head;         head.prev = newNode;         return newNode;     }      // Traverse the list to find the correct     // position to insert the new node     let curr = head;     while (curr.next !== null && curr.next.data < x) {         curr = curr.next;     }      // Insert the new node in the correct position     newNode.next = curr.next;     if (curr.next !== null) {         curr.next.prev = newNode;     }     curr.next = newNode;     newNode.prev = curr;      return head; }  function printList(curr) {     while (curr !== null) {         process.stdout.write(curr.data + " ");         curr = curr.next;     }     console.log(); }  // Create a hardcoded doubly linked list: // 3 <-> 5 <-> 8 <-> 10 <-> 12 let head = new Node(3); head.next = new Node(5); head.next.prev = head; head.next.next = new Node(8); head.next.next.prev = head.next; head.next.next.next = new Node(10); head.next.next.next.prev = head.next.next; head.next.next.next.next = new Node(12); head.next.next.next.next.prev = head.next.next.next;  const x = 9; head = sortedInsert(head, x); printList(head); 

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)



Next Article
Insert a Node after a given node in Doubly Linked List
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Linked List
  • doubly linked list
Practice Tags :
  • Linked List

Similar Reads

  • Sorted insert in a doubly linked list with head and tail pointers
    A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. The task is to create a doubly linked list by inserting nodes such that list rema
    10 min read
  • Insert a Node after a given node in Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node after a given node in the linked list. Examples: Input: Linked List = 1 <-> 2 <-> 4, newData = 3, key = 2Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node 3 is inserted after key, that is node 2.
    11 min read
  • Given a linked list which is sorted, how will you insert in sorted way
    Given a sorted linked list and a value to insert, write a function to insert the value in a sorted way.Initial Linked List Linked List after insertion of 9 Recommended PracticeInsert in a Sorted ListTry It! Algorithm: Let input linked list is sorted in increasing order. 1) If Linked list is empty th
    14 min read
  • Insert a Node before a given node in Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node before a given node in the linked list. Examples: Input: Linked List = 1 <-> 3 <-> 4, newData = 2, key = 3Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node with data 2 is inserted before the node
    12 min read
  • Insert a Node at the end of Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node at the end of the linked list. Examples: Input: Linked List = 1 <-> 2 <-> 3, NewNode = 4Output: Linked List = 1 <-> 2 <-> 3 <-> 4 Input: Linked List = NULL, NewNode = 1Output: Linked List = 1 Approach: Inserti
    9 min read
  • Sort linked list which is already sorted on absolute values
    Given a linked list that is sorted based on absolute values. Sort the list based on actual values. Examples: Input : 1 -> -10 output: -10 -> 1 Input : 1 -> -2 -> -3 -> 4 -> -5 output: -5 -> -3 -> -2 -> 1 -> 4 Input : -5 -> -10 Output: -10 -> -5 Input : 5 -> 10
    9 min read
  • Merge K sorted Doubly Linked List in Sorted Order
    Given K sorted doubly linked list. The task is to merge all sorted doubly linked list in single sorted doubly linked list means final list must be sorted.Examples: Input: List 1 : 2 <-> 7 <-> 8 <-> 12 <-> 15 <-> NULL List 2 : 4 <-> 9 <-> 10 <-> NULL Li
    15+ min read
  • Insertion in a Doubly Linked List
    Inserting a new node in a doubly linked list is very similar to inserting new node in linked list. There is a little extra work required to maintain the link of the previous node. In this article, we will learn about different ways to insert a node in a doubly linked list. Table of Content Insertion
    6 min read
  • Sort a nearly sorted doubly linked list
    Given a doubly linked list containing n nodes, each node is at most k-indices away from its target position. The problem is to sort the given doubly linked list. The distance can be assumed in either of the directions (left and right). Examples: Input: Doubly Linked List : 3 <-> 2 <-> 1
    15+ min read
  • Insert a node in Linked List before a given node
    Given a linked list, the task is to insert a new node with a specified value into a linked list before a node with a given key. Examples Input: head: 1 -> 2 -> 3 -> 4 -> 5 , newData = 6, key = 2Output: 1 -> 6 -> 2 -> 3 -> 4 -> 5 Explanation: After inserting node with value
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences