题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
// 利用multiset容器,元素可能重复
multiset<int> ms;
while(head)
{
ms.emplace(head->val);
head = head->next;
}
ListNode* ans = new ListNode(-1);
ListNode* temp = ans;
for(auto it=ms.begin(); it!=ms.end(); ++it)
{
ListNode* next = new ListNode(*it);
temp->next = next;
temp = temp->next;
}
return ans->next;
}
};
C++题库 文章被收录于专栏
非淡泊无以明志,非宁静无以致远
查看6道真题和解析