#include "iostream"
using namespace std;
/**Definition for singly-linked list.*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if (head==NULL||head->next==NULL) {
return head;
}
ListNode *p=head->next;//待排序
ListNode *res =new ListNode(0);//已排序
res->next=head;
head->next=NULL;
ListNode *preq=res;
ListNode *q=preq->next;
while (p!=NULL) {
while (q!=NULL&&p->val>q->val) {
preq=q;
q=q->next;
}
preq->next=p;
p=p->next;
preq=preq->next;
preq->next=q;
preq=res;
q=preq->next;
}
res->next=NULL;
delete res;
return q;
}
};
int main() {
ListNode *t=new ListNode(3);
t->next=new ListNode(2);
t->next->next=new ListNode(1);
cout<<t->val<<endl;
Solution so;
ListNode *res= so.insertionSortList(t);
cout<<res->val<<res->next->val<<endl;
return 0;
}
[leetcode] Insertion Sort List
最新推荐文章于 2021-12-07 09:13:28 发布