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;
    }
};
原文地址:https://www.cnblogs.com/qionglouyuyu/p/4853065.html