/*
* 给你链表的头结点 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 = []
* 输出:[]
*
*
* 提示:
*
* 链表中节点的数目在范围 [0, 5 * 104] 内
* -105 <= Node.val <= 105
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/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) {}
* };
*/
#include <stack>
#include <vector>
#include <iostream>
#include <random>
#include <stdint.h>
using namespace std;
class Solution {
public:
ListNode *sortList(ListNode *head)
{
if (head == nullptr) {
return head;
}
auto root = new (std::nothrow) ListNode(INT32_MIN, head);
auto p = head;
while (p->next != nullptr) {
auto current = p->next;
// current已经在正确的位置
if (current->val >= p->val) {
p = p->next;
continue;
}
// current和before->next做比较,插入适当的位置
auto before = root;
while (before->next->val <= current->val) {
before = before->next;
}
p->next = current->next;
current->next = before->next;
before->next = current;
}
head = root->next;
delete root;
return head;
}
};