LeetCode-147. Insertion Sort List

1. 题目

Insertion Sort List

Sort a linked list using insertion sort.
使用插入排序对链表排序。

2. 分析

插入排序的基本思想

3. 代码

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode dummy(INT_MIN);
        ListNode *cur = &dummy;

        while(head != NULL)
        {
            ListNode *t = head->next;
            cur = &dummy;

            while(cur->next != NULL && cur->next->val <= head->val)
                cur = cur->next;

            head->next = cur->next;
            cur->next = head;
            head = t;
        }

        return dummy.next;
    }
};

完整源代码放于github

猜你喜欢

转载自blog.csdn.net/tao_ba/article/details/80613583