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

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →