题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <algorithm>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
auto Size = [&head](){
int cnt = 0;
for(auto cur = head; cur; cur = cur->next) {
cnt ++;
}
return cnt;
};
std::vector<int> li;
li.reserve(Size());
for(auto cur = head; cur; cur = cur->next) {
li.emplace_back(cur->val);
}
sort(li.begin(), li.end());
// 如何并行遍历?
for(auto [vit, lit] = std::make_pair(li.cbegin(), head); lit; ++vit, lit = lit->next) {
lit->val = *vit;
}
return head;
}
};
查看7道真题和解析