Insert into a cyclic sorted list

Given a node from a cyclic linked list which has been sorted, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be any single node in the list.

01 void insertSortedCycle(Node** head, int k)
02 {
03     if(*head==NULL){
04         Node* enode=new Node;
05         enode->value=k;
06         enode->next=enode;
07         *head=enode;
08     }else{
09         Node* prv=*head;
10         Node* tmp=prv->next;
11         while(true){
12             if((k>prv->value)&&(k<tmp->value))
13                 break;
14             if(((k>prv->value)||(k<tmp->value))
15                 &&(prv->value>tmp->value))
16                 break;
17             if(tmp==*head)
18                 break;
19             prv=tmp;
20             tmp=tmp->next;
21         }
22         Node* enode= new Node;
23         enode->value=k;
24         enode->next=tmp;
25         prv->next=enode;
26         return;
27     }
28 }
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s