题目:
代码(首刷看解析 2024年3月5日):
/**
* 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) {
if (!head) return nullptr;
vector<ListNode*> myvec;
while (head) {
myvec.push_back(head);
head = head->next;
}
sort(myvec.begin(), myvec.end(), [](auto& a, auto& b){return a->val < b->val;});
for (int i = 0; i < myvec.size(); ++i) {
if(i != myvec.size() - 1) {
myvec[i]->next = myvec[i + 1];
} else {
myvec[i]->next = nullptr;
}
}
return myvec[0];
}
};
代码(二刷debug on GPT,2024年9月5日)
auto cmp = [](ListNode* a, ListNode* b){
return a->val > b->val;
};
class Solution {
public:
ListNode* sortList(ListNode* head) {
priority_queue<ListNode*, vector<ListNode*>,decltype(cmp)> pq(cmp);
auto cur = head;
while(cur) {
pq.push(cur);
cur = cur->next;
}
auto dummyHead = new ListNode(0);
cur = dummyHead;
while(!pq.empty()) {
cur->next = pq.top();
pq.pop();
cur = cur->next;
}
cur->next = nullptr;
return dummyHead->next;
}
};