Sorted insert for circular linked list

PROBLEM :

Given a sorted circular linked list, insert a newnode so that it remains a sorted circular linked list.

 For example,
 if the input CLL is following.



After insertion of 7, the above CLL should be changed to following



Input:

In this problem, method takes two argument: the address of the head of the linked list and the data which you have to insert. The function should not read any input from stdin/console.
The Node structure has a data part which stores the data and a next pointer which points to the next element of the linked list.
There are multiple test cases. For each test case, this method will be called individually.

Output:
Set the * head_ref to head of resultant linked list.

Note: If you use "Test" or "Expected Output Button" use below example format

Constraints:

1<=T<=100
0<=N<=200

Example:

Input:
2
3                           Size of Linked List
1 2 4                    Elements of Linked List
2                           Element to be inserted
4
1 4 7 9
5

Output:

1 2 2 4
1 4 5 7 9

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/* structure for a node */
/*
struct node
{
  int data;
  struct node *next;
};
 */
void sortedInsert(struct node** head_ref, int x)
{
    struct node *temp,*ptr ;
    temp=(*head_ref) ;
   
    ptr=(struct node*)malloc(sizeof(struct node)) ;
    ptr->data=x ;
    ptr->next=NULL ;
   
    if((*head_ref)==NULL)
    {
        ptr->next=ptr ;
        (*head_ref)=ptr ;
        return ;
    }
   
    while(temp->next!=(*head_ref))
        temp=temp->next ;
       
    if(temp->data>ptr->data&&(*head_ref)->data>ptr->data)
    {
        ptr->next=temp->next ;
        temp->next=ptr ;
        (*head_ref)=ptr ;
        return ;
    }
   
    temp=(*head_ref) ;
   
    while(temp->next!=(*head_ref)&&temp->next->data<=ptr->data)
        temp=temp->next ;
       
    if(temp->next==(*head_ref))
    {
        ptr->next=temp->next ;
        temp->next=ptr ;

        return ;
    }
   
    ptr->next=temp->next ;
        temp->next=ptr ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )