题解 | #单链表的排序#
单链表的排序
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
//vector<int>a;
ListNode* p=head;
int len=0;
while(p){
p=p->next;
len++;
}
int a[len];
for(int i=0;i<len;i++){
//a.push_back(head->val);
a[i]=head->val;
head=head->next;
}
sort(a, a + len);
ListNode* q=new ListNode(0);
ListNode* p1=q;
int j=0;
while(j<len){
q->next= new ListNode(a[j]);
q=q->next;
j++;
}
return p1->next;
}
};
查看6道真题和解析