Insertion Sort List

Sort a linked list using insertion sort.

 

Code:

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if(head==NULL) return head;
        ListNode *start=new ListNode(0);
        start->next=head;
        ListNode *pre=head;
        ListNode *cur=head->next;
        ListNode *nex;
        while(cur){
            ListNode *p0=start;
            ListNode *p1=start->next;
            nex=cur->next;
            while(p1!=cur){
                if(cur->val<p1->val){
                    p0->next=cur;
                    cur->next=p1;
                    pre->next=nex;
                    break;
                }
                p0=p1;
                p1=p1->next;
                if(p1==cur) // if cur isn't removed, pre moves forward; If cur is removed, pre doesn't need to change.
                    pre=cur;
            }
            cur=nex;
        }
        head=start->next;
        delete start;
        return head;
    }
};

 

posted @ 2013-11-14 06:06  WinsCoder  阅读(144)  评论(0编辑  收藏  举报