排序链表
题目链接:排序链表
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
方法一:额外数组
/**
* 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) {
multiset<int> s;
ListNode* cur = head;
while (cur) {
s.insert(cur->val);
cur = cur->next;
}
cur = head;
for (auto num : s) {
cur->val = num;
cur = cur->next;
}
return head;
}
};