题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
// 利用stl库中的sort和vector来进行排序,并将排序后的数据放回到原来的链表中。
*/
#include <algorithm>
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
if (head == nullptr) return nullptr;
// write code here
ListNode* p = head;
std::vector<int> vi;
while (p!= nullptr) {
vi.push_back(p->val);
p = p->next;
}
std::sort(vi.begin(), vi.end());
p = head;
for (int i = 0;i < vi.size(); ++i) {
p->val = vi[i];
p = p->next;
}
return head;
}
};
查看16道真题和解析
