leetcode_sort-list

题目链接

sort-list

题目内容

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

进阶:

你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?

示例 1

输入:head = [4,2,1,3]
输出:[1,2,3,4]

示例 2

输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]

示例 3

输入:head = []
输出:[]

解题思路

https://www.cnblogs.com/unclejokermr/p/14013526.html这题的解题思路一样。

代码


class Solution {
public:
    ListNode* sortList(ListNode* head) {
              if (head == nullptr) {
            return head;
        }
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode* lastSorted = head;
        ListNode* curr = head->next;
        while (curr != nullptr) {
            if (lastSorted->val <= curr->val) {
                lastSorted = lastSorted->next;
            } else {
                ListNode *prev = dummyHead;
                while (prev->next->val <= curr->val) {
                    prev = prev->next;
                }
                lastSorted->next = curr->next;
                curr->next = prev->next;
                prev->next = curr;
            }
            curr = lastSorted->next;
        }
        return dummyHead->next;
    }
};
posted @ 2020-11-21 23:56  位军营  阅读(55)  评论(0编辑  收藏  举报