/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(head==nullptr) return nullptr;
ListNode*s=new ListNode(0);
s->next=head;
ListNode*last=head;
ListNode*cur=head->next;
while(cur){
if(last->val<=cur->val){
last=cur;
cur=cur->next;
}
else{
ListNode*pre=s;
while(pre->next!=nullptr&&pre->next->val<=cur->val) pre=pre->next;
last->next=cur->next;
cur->next=pre->next;
pre->next=cur;
cur=last->next;
}
}
return s->next;
}
};
147. 对链表进行插入排序
最新推荐文章于 2024-10-08 10:36:00 发布