Insert an element in a sorted circular linkedList.[Microsoft & Amazon]

Problem:Given a sorted circular linked list, insert a new node so that it remains a sorted circular linked list.

Problem Link

/*
struct node
{
  int data;
  struct node *next;
};
 */
void sortedInsert(struct node** head_ref, int x)
{
    node *tmp=(*head_ref);
    node *prev,*nxt;
    int val;
    int start_val=tmp->data;
    bool first=1;
    node *p=new node;
    p->data=x;
    if(x<tmp->data)
    {
        int tmpdata=(*head_ref)->data;
        nxt=(*head_ref)->next;
        (*head_ref)->data=x;
        p->data=tmpdata;
        (*head_ref)->next=p;
        p->next=nxt;
        return;
    }
    while(tmp)
    {
        val=tmp->data;
        if(val!=start_val)
        first=0;
        if(val==x)
        {
             nxt=tmp->next;
             prev=tmp;
             prev->next=p;
             p->next=nxt;
            return;
        }
        if(val<x)
        {
            prev=tmp;
            nxt=tmp->next;
            if(nxt->data>x)
            {
                prev->next=p;
                p->next=nxt;
                return;
            }
			else if(nxt->data<x)
			{
				if(first==0 && nxt->data==start_val)
				{
					prev->next=p;
					p->next=nxt;
					return;
				}
			}
        }
        tmp=tmp->next;
    }
  }

 

Leave a Reply

Your email address will not be published. Required fields are marked *