首页 > 代码库 > Insertion Sort List

Insertion Sort List

思路:这里新建一个list方便插入排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode dummy(INT_MIN);
        //dummy.next = head;
        
        ListNode *cur = head;
        while(cur)
        {
            ListNode *prev = nullptr;
            for(ListNode *tmp=&dummy; tmp != nullptr && tmp->val <= cur->val; prev = tmp, tmp = tmp->next);
            
            ListNode *tmpNode = cur->next;
            cur->next = prev->next;
            prev->next = cur;
            cur = tmpNode;
        }
        
        return dummy.next;
    }
};

 

Insertion Sort List