Skip to content

Instantly share code, notes, and snippets.

@bluesunxu
Created December 18, 2012 03:57
Show Gist options
  • Save bluesunxu/4324871 to your computer and use it in GitHub Desktop.
Save bluesunxu/4324871 to your computer and use it in GitHub Desktop.
Insertion to a cyclic sorted list given a pointer to a random node in the list.
node* icsl_2(node* head, node* n) {
if(!head) {
// list is empty, set head to the new node.
return (head = n->next = n);
}
node* cur=head;
node* prev;
do {
prev = cur;
cur = cur->next;
// normal situation
if((prev->value <= n->value) && (n->value <= cur->value)) break;
// new element is larger than the biggest or less than the smallest.
if((prev->value > cur->value) &&
(n->value < cur->value || n->value > prev->value))
break;
} while (cur != head);
n->next = cur;
prev->next = n;
return head;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment