Problem:Given a sorted circular linked list, insert a new node so that it remains a sorted circular linked list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
/* 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; } } |