147. Insertion Sort List (List)

Sort a linked list using insertion sort.

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if(!head || !head->next) return head;
        ListNode *tail =head->next;
        head->next = NULL;
        ListNode *current;
        ListNode *tmp;
        
        while(tail){
            if(tail->val < head->val){
                tmp = tail->next;
                tail->next = head;
                head = tail;
                tail = tmp;
                continue;
            } 
            
            current = head;
            while(current->next && tail->val >= current->next-> val)  current = current->next;
            tmp = tail->next;
            tail->next = current->next;
            current->next = tail;
            tail = tmp;
        }
        return head;
    }
};

 

posted on 2015-10-03 09:39  joannae  阅读(145)  评论(0编辑  收藏  举报

导航