题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <algorithm>
#include <vector>
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
if (head==nullptr) {
return head;
}
vector<int> num;
ListNode * temp=head;
while (temp!=nullptr) {
num.push_back(temp->val);
temp=temp->next;
}
sort(num.begin(), num.end());
int i=0;
ListNode * re=head;
while (head!=nullptr) {
head->val=num.at(i);
head=head->next;
i++;
}
return re;
}
};
查看14道真题和解析