题解 | 单链表的排序
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
#include<vector>
#include<algorithm>
using namespace std;
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
vector<int>data;
ListNode* second=head;
int i=0;
while(second!=nullptr){
data.push_back(second->val);
second=second->next;
i++;}
sort(data.begin(),data.end());
ListNode* curr=new ListNode(data[0]);
ListNode* Head=curr;
for(int p=1;p<i;p++){
curr->next=new ListNode(data[p]);
curr=curr->next;
}
return Head;
}
};
查看6道真题和解析