Inserting a Node Into a Sorted Doubly Linked List


Problem Statement :


Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort.

Example

head  refers  to the list 1 <-> 2 <-> 4 - > NULL.
data = 3

Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL ,

Function Description

Complete the sortedInsert function in the editor below.

sortedInsert has two parameters:

DoublyLinkedListNode pointer head: a reference to the head of a doubly-linked list

int data: An integer denoting the value of the data field for the DoublyLinkedListNode you must insert into the list.

Returns

DoublyLinkedListNode pointer: a reference to the head of the list

Note: Recall that an empty list (i.e., where head = NULL ) and a list with one element are sorted lists.

nput Format

The first line contains an integer t, the number of test cases.

Each of the test case is in the following format:

The first line contains an integer n, the number of elements in the linked list.
Each of the next n lines contains an integer, the data for each node of the linked list.
The last line contains an integer, data , which needs to be inserted into the sorted doubly-linked list.



Solution :



title-img


                            Solution in C :

In C++ :


/*
    Insert Node in a doubly sorted linked list 
    After each insertion, the list should be sorted
   Node is defined as
   struct Node
   {
     int data;
     Node *next;
     Node *prev
   }
*/
Node* SortedInsert(Node *head,int data)
{
    // Complete this function
   // Do not write the main method. 
    Node *current = NULL;
    Node *new_node = (Node*)malloc(sizeof(Node));
    new_node->data=data;
    new_node->next=NULL;
    new_node->prev=NULL;
    
  if (head == NULL )
  {
    head = new_node; 
  }
  else if(head->data >= new_node->data)
  {
    new_node->next = head;
    head->prev=new_node;
    head = new_node; 
  }
  else
  {
    
    current = head;
    while (current->next!=NULL && current->next->data < new_node->data)
    {
      current = current->next;
    }
      
      if(current->next!=NULL)
      {
          new_node->next = current->next;
          current->next->prev=new_node;
      }     
      current->next = new_node;
      new_node->prev=current;
      
  }       
    return head;
}



In Java :


/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  class Node {
     int data;
     Node next;
     Node prev;
  }
*/

Node SortedInsert(Node head,int data) {
  
    Node n= new Node();
    n.data=data;
    n.next=null;
    n.prev=null;
    
    if(head==null)
        return n;
    if(head.data > data)
        {
        
        n.next=head;
        head.prev=n;
        return n;
    }
    
    Node temp=head;
    
    while(temp.next!=null)
        {
           
         if(temp.next.data > data)
             {
             
               n.next=temp.next;
               n.prev=temp.next.prev;
               temp.next=n;
               n.next.prev=n;
               return head;
         }
        temp=temp.next;
        
    }
    
    temp.next=n;
    n.prev=temp;
    return head;
    
}




In python3 :



"""
 Insert a node into a sorted doubly linked list
 head could be None as well for empty list
 Node is defined as
 
 class Node(object):
 
   def __init__(self, data=None, next_node=None, prev_node = None):
       self.data = data
       self.next = next_node
       self.prev = prev_node

 return the head node of the updated list 
"""
def SortedInsert(head, data):
    new = Node(data=data)
    tmp = head
    while tmp.data <= data and tmp.next != None and tmp.next.data <= data:
        tmp = tmp.next
    new.prev = tmp
    new.next = tmp.next
    tmp.next = new
    if new.next != None:
        new.next.prev = new
    return head
  





In C :



// Complete the sortedInsert function below.

/*
 * For your reference:
 *
 * DoublyLinkedListNode {
 *     int data;
 *     DoublyLinkedListNode* next;
 *     DoublyLinkedListNode* prev;
 * };
 *
 */
DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* head, int data) {
    
    DoublyLinkedListNode *New = create_doubly_linked_list_node(data);
    if (!head)
    {
        head = New;
        return head;
    }
    else if (data < (head->data))
    {
        New->next = head; 
        head->prev = New;
        New->prev = NULL;
        head = New;
        return head; 
    }
    else 
    {
        DoublyLinkedListNode *temp = head;
        while ( ((temp->next) != NULL) && ((temp->next->data) <= data))
            temp = temp->next;
        
        if (temp->next != NULL)
        {
            DoublyLinkedListNode *next = temp->next;
            next->prev = New;
            New->next = next;
        }
        else 
            New->next = NULL;
            
        temp->next = New;
        New->prev = temp;
    }
    return head; 
}
                        








View More Similar Problems

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →