Open In App

Sorted insert in a doubly linked list with head and tail pointers

Last Updated : 11 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 remains in ascending order on printing from left to right. Also, we need to maintain two pointers, head (points to first node) and tail (points to last node).

Examples:  

Input : 40 50 10 45 90 100 95
Output :10 40 45 50 90 95 100

Input : 30 10 50 43 56 12
Output :10 12 30 43 50 56

Algorithm: 

The task can be accomplished as: 

  1. If Linked list is empty then make both the left and right pointers point to the node to be inserted and make its previous and next field point to NULL.
  2. If node to be inserted has value less than the value of first node of linked list then connect that node from previous field of first node.
  3. If node to be inserted has value more than the value of last node of linked list then connect that node from next field of last node.
  4. If node to be inserted has value in between the value of first and last node, then check for appropriate position and make connections.

Implementation:

C++




/* C++ program to insetail nodes in doubly 
linked list such that list remains in 
ascending order on printing from left 
to right */
#include <bits/stdc++.h>
using namespace std;
  
// A linked list node 
class Node 
    public:
    Node *prev; 
    int info; 
    Node *next; 
}; 
  
// Function to insetail new node 
void nodeInsetail(Node **head, 
                Node **tail, 
                int key) 
  
    Node *p = new Node(); 
    p->info = key; 
    p->next = NULL; 
  
    // If first node to be insetailed in doubly 
    // linked list 
    if ((*head) == NULL) 
    
        (*head) = p; 
        (*tail) = p; 
        (*head)->prev = NULL; 
        return
    
  
    // If node to be insetailed has value less 
    // than first node 
    if ((p->info) < ((*head)->info)) 
    
        p->prev = NULL; 
        (*head)->prev = p; 
        p->next = (*head); 
        (*head) = p; 
        return
    
  
    // If node to be insetailed has value more 
    // than last node 
    if ((p->info) > ((*tail)->info)) 
    
        p->prev = (*tail); 
        (*tail)->next = p; 
        (*tail) = p; 
        return
    
  
    // Find the node before which we need to 
    // insert p. 
    Node *temp = (*head)->next; 
    while ((temp->info) < (p->info)) 
        temp = temp->next; 
  
    // Insert new node before temp 
    (temp->prev)->next = p; 
    p->prev = temp->prev; 
    temp->prev = p; 
    p->next = temp; 
  
// Function to print nodes in from left to right 
void printList(Node *temp) 
    while (temp != NULL) 
    
        cout << temp->info << " "
        temp = temp->next; 
    
  
// Driver program to test above functions 
int main() 
    Node *left = NULL, *right = NULL; 
    nodeInsetail(&left, &right, 30); 
    nodeInsetail(&left, &right, 50); 
    nodeInsetail(&left, &right, 90); 
    nodeInsetail(&left, &right, 10); 
    nodeInsetail(&left, &right, 40); 
    nodeInsetail(&left, &right, 110); 
    nodeInsetail(&left, &right, 60); 
    nodeInsetail(&left, &right, 95); 
    nodeInsetail(&left, &right, 23); 
  
    cout<<"Doubly linked list on printing"
        " from left to right\n"
    printList(left); 
  
    return 0; 
  
// This is code is contributed by rathbhupendra


C




/* C program to insetail nodes in doubly
linked list such that list remains in
ascending order on printing from left
to right */
#include<stdio.h>
#include<stdlib.h>
  
// A linked list node
struct Node
{
    struct Node *prev;
    int info;
    struct Node *next;
};
  
// Function to insetail new node
void nodeInsetail(struct Node **head,
                  struct Node **tail,
                  int key)
{
  
    struct Node *p = new Node;
    p->info = key;
    p->next = NULL;
  
    // If first node to be insetailed in doubly
    // linked list
    if ((*head) == NULL)
    {
        (*head) = p;
        (*tail) = p;
        (*head)->prev = NULL;
        return;
    }
  
    // If node to be insetailed has value less
    // than first node
    if ((p->info) < ((*head)->info))
    {
        p->prev = NULL;
        (*head)->prev = p;
        p->next = (*head);
        (*head) = p;
        return;
    }
  
    // If node to be insetailed has value more
    // than last node
    if ((p->info) > ((*tail)->info))
    {
        p->prev = (*tail);
        (*tail)->next = p;
        (*tail) = p;
        return;
    }
  
    // Find the node before which we need to
    // insert p.
    temp = (*head)->next;
    while ((temp->info) < (p->info))
        temp = temp->next;
  
    // Insert new node before temp
    (temp->prev)->next = p;
    p->prev = temp->prev;
    temp->prev = p;
    p->next = temp;
}
  
// Function to print nodes in from left to right
void printList(struct Node *temp)
{
    while (temp != NULL)
    {
        printf("%d ", temp->info);
        temp = temp->next;
    }
}
  
// Driver program to test above functions
int main()
{
    struct Node *left = NULL, *right = NULL;
    nodeInsetail(&left, &right, 30);
    nodeInsetail(&left, &right, 50);
    nodeInsetail(&left, &right, 90);
    nodeInsetail(&left, &right, 10);
    nodeInsetail(&left, &right, 40);
    nodeInsetail(&left, &right, 110);
    nodeInsetail(&left, &right, 60);
    nodeInsetail(&left, &right, 95);
    nodeInsetail(&left, &right, 23);
  
    printf("\nDoubly linked list on printing"
           " from left to right\n");
    printList(left);
  
    return 0;
}


Java




/* Java program to insetail nodes in doubly 
linked list such that list remains in 
ascending order on printing from left 
to right */
  
import java.io.*;
import java.util.*;
  
// A linked list node
class Node
{
    int info;
    Node prev, next;
}
  
class GFG
{
  
    static Node head, tail;
  
    // Function to insetail new node 
    static void nodeInsetail(int key)
    {
        Node p = new Node();
        p.info = key;
        p.next = null;
  
        // If first node to be insetailed in doubly 
        // linked list
        if (head == null)
        {
            head = p;
            tail = p;
            head.prev = null;
            return;
        }
  
        // If node to be insetailed has value less 
        // than first node 
        if (p.info < head.info)
        {
            p.prev = null;
            head.prev = p;
            p.next = head;
            head = p;
            return;
        }
              
        // If node to be insetailed has value more 
        // than last node 
        if (p.info > tail.info)
        {
            p.prev = tail;
            tail.next = p;
            tail = p;
            return;
        }
  
        // Find the node before which we need to 
        // insert p.
        Node temp = head.next;
        while (temp.info < p.info)
                temp = temp.next;
                  
        // Insert new node before temp 
        (temp.prev).next = p;
        p.prev = temp.prev;
        temp.prev = p;
        p.next = temp;
    }
  
    // Function to print nodes in from left to right
    static void printList(Node temp)
    {
        while (temp != null)
        {
                System.out.print(temp.info + " ");
                temp = temp.next;
        }
    }
  
    // Driver code
    public static void main(String args[])
    {
        head = tail = null;
        nodeInsetail(30);
        nodeInsetail(50);
        nodeInsetail(90);
        nodeInsetail(10);
        nodeInsetail(40);
        nodeInsetail(110);
        nodeInsetail(60);
        nodeInsetail(95);
        nodeInsetail(23);
  
        System.out.println("Doubly linked list on printing from left to right");
        printList(head); 
    }
}
  
// This code is contributed by rachana soma


Python




# Python program to insetail nodes in doubly 
# linked list such that list remains in 
# ascending order on printing from left 
# to right 
  
# Linked List node 
class Node: 
    def __init__(self, data): 
        self.info = data 
        self.next = None
        self.prev = None
  
head = None
tail = None
                  
# Function to insetail new node 
def nodeInsetail( key) :
  
    global head
    global tail
      
    p = Node(0
    p.info = key 
    p.next = None
  
    # If first node to be insetailed in doubly 
    # linked list 
    if ((head) == None) :
        (head) =
        (tail) =
        (head).prev = None
        return
      
    # If node to be insetailed has value less 
    # than first node 
    if ((p.info) < ((head).info)) :
        p.prev = None
        (head).prev =
        p.next = (head) 
        (head) =
        return
  
    # If node to be insetailed has value more 
    # than last node 
    if ((p.info) > ((tail).info)) :
      
        p.prev = (tail) 
        (tail).next =
        (tail) =
        return
      
    # Find the node before which we need to 
    # insert p. 
    temp = (head).next
    while ((temp.info) < (p.info)) :
        temp = temp.next
  
    # Insert new node before temp 
    (temp.prev).next =
    p.prev = temp.prev 
    temp.prev =
    p.next = temp 
  
# Function to print nodes in from left to right 
def printList(temp) :
  
    while (temp != None) :
      
        print( temp.info, end = " "
        temp = temp.next
      
# Driver program to test above functions 
nodeInsetail( 30
nodeInsetail( 50
nodeInsetail( 90
nodeInsetail( 10
nodeInsetail( 40
nodeInsetail( 110
nodeInsetail( 60
nodeInsetail( 95
nodeInsetail( 23
  
print("Doubly linked list on printing from left to right\n" )
  
printList(head) 
  
# This code is contributed by Arnab Kundu


C#




/* C# program to insetail nodes in doubly 
linked list such that list remains in 
ascending order on printing from left 
to right */
using System; 
  
// A linked list node 
public class Node 
    public int info; 
    public Node prev, next; 
  
class GFG 
  
    static Node head, tail; 
  
    // Function to insetail new node 
    static void nodeInsetail(int key) 
    
        Node p = new Node(); 
        p.info = key; 
        p.next = null
  
        // If first node to be insetailed in doubly 
        // linked list 
        if (head == null
        
            head = p; 
            tail = p; 
            head.prev = null
            return
        
  
        // If node to be insetailed has value less 
        // than first node 
        if (p.info < head.info) 
        
            p.prev = null
            head.prev = p; 
            p.next = head; 
            head = p; 
            return
        
              
        // If node to be insetailed has value more 
        // than last node 
        if (p.info > tail.info) 
        
            p.prev = tail; 
            tail.next = p; 
            tail = p; 
            return
        
  
        // Find the node before which we need to 
        // insert p. 
        Node temp = head.next; 
        while (temp.info < p.info) 
            temp = temp.next; 
                  
        // Insert new node before temp 
        (temp.prev).next = p; 
        p.prev = temp.prev; 
        temp.prev = p; 
        p.next = temp; 
    
  
    // Function to print nodes in from left to right 
    static void printList(Node temp) 
    
        while (temp != null
        
            Console.Write(temp.info + " "); 
            temp = temp.next; 
        
    
  
    // Driver code 
    public static void Main(String []args) 
    
        head = tail = null
        nodeInsetail(30); 
        nodeInsetail(50); 
        nodeInsetail(90); 
        nodeInsetail(10); 
        nodeInsetail(40); 
        nodeInsetail(110); 
        nodeInsetail(60); 
        nodeInsetail(95); 
        nodeInsetail(23); 
  
        Console.WriteLine("Doubly linked list on printing from left to right"); 
        printList(head); 
    
  
// This code is contributed by Arnab Kundu


Javascript




<script>
/* javascript program to insetail nodes in doubly 
linked list such that list remains in 
ascending order on printing from left 
to right */
  
// A linked list node
 class Node {
        constructor() {
            this.info = 0;
            this.prev = null;
            this.next = null;
        }
    }
var head, tail;
  
    // Function to insetail new node
    function nodeInsetail(key) {
         p = new Node();
        p.info = key;
        p.next = null;
  
        // If first node to be insetailed in doubly
        // linked list
        if (head == null) {
            head = p;
            tail = p;
            head.prev = null;
            return;
        }
  
        // If node to be insetailed has value less
        // than first node
        if (p.info < head.info) {
            p.prev = null;
            head.prev = p;
            p.next = head;
            head = p;
            return;
        }
  
        // If node to be insetailed has value more
        // than last node
        if (p.info > tail.info) {
            p.prev = tail;
            tail.next = p;
            tail = p;
            return;
        }
  
        // Find the node before which we need to
        // insert p.
         temp = head.next;
        while (temp.info < p.info)
            temp = temp.next;
  
        // Insert new node before temp
        (temp.prev).next = p;
        p.prev = temp.prev;
        temp.prev = p;
        p.next = temp;
    }
  
    // Function to print nodes in from left to right
    function printList( temp) {
        while (temp != null) {
            document.write(temp.info + " ");
            temp = temp.next;
        }
    }
  
    // Driver code
      
        head = tail = null;
        nodeInsetail(30);
        nodeInsetail(50);
        nodeInsetail(90);
        nodeInsetail(10);
        nodeInsetail(40);
        nodeInsetail(110);
        nodeInsetail(60);
        nodeInsetail(95);
        nodeInsetail(23);
  
        document.write("Doubly linked list on printing from left to right<br/>");
        printList(head);
  
// This code is contributed by aashish1995
</script>


Output

Doubly linked list on printing from left to right
10 23 30 40 50 60 90 95 110 

Time complexity: O(n) since using a single loop to traverse doubly linked list
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Insert value in sorted way in a sorted doubly linked list
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 Recommended PracticeInsert in Sorted way in a Sorted DLLTry It! Algorithm: Let input doubly linked list is sorted in increasing order. New node passed to the function contains
9 min read
Tail vs. Non-Tail Recursion
Tail recursion and Non-tail recursion are two types of recursive functions in computer programming. In this post we will deep dive into what are the major differences between the tail and non-tail recursion. 1) Definition:Tail recursion is defined by having the recursive call as the last operation in the function before returningfunction factorial
3 min read
Convert Binary Tree to Doubly Linked List by fixing left and right pointers
Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL). The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as in Inorder for the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the
12 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 &lt;-&gt; 7 &lt;-&gt; 8 &lt;-&gt; 12 &lt;-&gt; 15 &lt;-&gt; NULL List 2 : 4 &lt;-&gt; 9 &lt;-&gt; 10 &lt;-&gt; NULL List 3 : 5 &lt;-&gt; 9 &lt;-&gt; 11 &lt;-&gt; 16
18 min read
Number of sequences which has HEAD at alternate positions to the right of the first HEAD
Given that a coin is tossed N times. The task is to find the total number of the sequence of tosses such that after the first head from left, all the alternating positions to the right of it are occupied by the head only. The positions except the alternating position can be occupied by any of head or tail. For example, if you are tossing a coin 10
6 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 then make the node as head and return it. 2) If the
14 min read
Sorted merge of two sorted doubly circular linked lists
Given two sorted Doubly circular Linked List containing n1 and n2 nodes respectively. The problem is to merge the two lists such that resultant list is also in sorted order.Example:  List 1:   List 2:   Final list:  Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: Following are the steps: If head1 ==
23 min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node. Introduction to Doubly linked list : A Doubly Linked List (D
2 min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
Practice Tags :