程式語言 - LeetCode - C++ - 147. Insertion Sort List



題目:


解答:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if (!head) {
            return head;
        }

        ListNode d0;
        ListNode *cur = head;

        while (cur) {
            ListNode *pre = &d0;

            while (pre->next && pre->next->val < cur->val) {
                pre = pre->next;
            }

            ListNode *next = cur->next;
            cur->next = pre->next;
            pre->next = cur;
            cur = next;
        }

        return d0.next;
    }
};