[LeetCode] 147. 对链表进行插入排序(Insertion Sort List)

本文已收录于 LeetCode刷题 系列,共计 28 篇,本篇是第 12 篇

本文已收录到:LeetCode刷题 专题

[title]题目[/title]

插入排序算法:

插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
重复直到所有输入数据插入完为止。
示例 1:

输入: 4->2->1->3
输出: 1->2->3->4
示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insertion-sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

[title]视频讲解[/title]

[bilibili cid=”” page=”1″]540149966[/bilibili]

 

[title]简明思路[/title]

[title]代码[/title]

/**
 * 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(0);
        ListNode* pre = &dummy;
        pre->next = head;
        
        ListNode* cur = head;
        ListNode* temp = nullptr;

        while (cur != nullptr && cur->next != nullptr)
        {
            if (cur->next->val >= cur->val)
            {
                cur = cur->next;
            }
            else
            {
                temp = cur->next;
                cur->next = cur->next->next;
                pre = &dummy;
                while (pre->next->val  <= temp->val)
                {
                    pre = pre->next;
                }
                temp->next = pre->next;
                pre->next = temp;
            }
        }
        return dummy.next;
    }
};

 

作者: 高志远

高志远,24岁,男生

《[LeetCode] 147. 对链表进行插入排序(Insertion Sort List)》有一条评论

发表评论

邮箱地址不会被公开。