Skip to content

Instantly share code, notes, and snippets.

@zsh-89
Created November 20, 2013 07:09
Show Gist options
  • Save zsh-89/7558970 to your computer and use it in GitHub Desktop.
Save zsh-89/7558970 to your computer and use it in GitHub Desktop.
typedef ListNode LNode;
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if (!head) return NULL;
LNode *newHead=head; LNode *p=head->next;
newHead->next=NULL;
while (p) {
LNode *cur=p; p=p->next;
newHead=insert(newHead, cur);
}
return newHead;
}
LNode* insert(LNode *head, LNode *x){
LNode *pre=NULL; LNode *cur=head;
while (cur && cur->val < x->val) {
pre=cur; cur=cur->next;
}
if (pre==NULL) {
x->next=head;
return x;
}
x->next=cur;
pre->next=x;
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment