题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool mycmp(ListNode* h1,ListNode* h2)
{
return h1->val<h2->val;
}
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
vector<ListNode*> vc;
ListNode* current =head;
while(current)
{
vc.emplace_back(current);
current=current->next;
}
sort(vc.begin(),vc.end(),mycmp);
int l=0,r=1;
while(r<vc.size())
{
vc[l]->next=vc[r];
r++,l++;
}
vc[l]->next=nullptr;
return vc[0];
}
};