147. Insertion Sort List
Total Accepted: 66609
Total Submissions: 230331
Difficulty: Medium
Sort a linked list using insertion sort.
Subscribe to see which companies asked this question
Have you met this question in a real interview?
链接: https://leetcode.com/problems/insertion-sort-list/
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
#include<set>
typedef long long ll;
#define eps 1e-8
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define bug printf("hi"\n)
using namespace std;
#define INF 0x3f3f3f3f
#define N 30
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){
}
};
void show(ListNode * head)
{
while(head)
{
printf("%d ",head->val);
head=head->next;
}
printf("\n");
}
class Solution{
public:
ListNode *insertionSortList(ListNode * head)
{
if(head==NULL||head->next==NULL) return head;
ListNode* pre=new ListNode(0);
quicksort(pre,head,NULL);
head=pre->next;
delete pre;
return head;
}
ListNode * quicksort(ListNode* pre,ListNode * head,ListNode *tail)
{
if(head==tail) return head;
if(head->next==NULL) return head;
ListNode * mid=getpos(pre,head,tail);
quicksort(pre,pre->next,mid);
quicksort(mid,mid->next,tail);
return pre;
}
ListNode * getpos(ListNode* pre,ListNode *head,ListNode * tail)
{
ListNode *small=new ListNode(0),*big=new ListNode(0);
ListNode *ss=small,*bb=big;
for(ListNode * it=head->next;it!=tail;it=it->next)
if(it->val<=head->val)
{
small->next=it;
small=it;
}
else
{
big->next=it;
big=it;
}
big->next=tail;
head->next=bb->next;
small->next=head;
pre->next=ss->next;
delete bb;
delete ss;
return head;
}
};
int main()
{
int i,j;
ListNode * head=new ListNode(3);
ListNode * tail=head;
for(int i=2;i>=1;i--)
{
ListNode * temp=new ListNode(i);
tail->next=temp;
tail=temp;
}
show(head);
Solution ans;
tail=ans.insertionSortList(head);
show(tail);
return 0;
}