给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:
输入:head = []
输出:[]
来源:力扣(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) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
vector<int> res;
ListNode *p = head;
if(!head)
return head;
while(p) {
res.emplace_back(p->val);
p = p->next;
}
sort(res.begin(), res.end());
p = head;
int i = 0;
while(p) {
p->val = res[i++];
p = p->next;
}
return head;
}
};