题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <vector>
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
//用线性表存数,然后在表内排序,最后还原到链表
vector<int> sqList;
ListNode* p=head;
while(p){
sqList.push_back(p->val);
p=p->next;
}
sort(sqList.begin(),sqList.end());
p=head;
int i=0;
while(p){
p->val=sqList[i];
p=p->next;
i++;
}
return head;
}
};

查看21道真题和解析