排序链表-常规方法,数组存储加快速排序
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
输入:head = [4,2,1,3] 输出:[1,2,3,4]
输入:head = [-1,5,3,4,0] 输出:[-1,0,3,4,5]
示例 3:
输入:head = [] 输出:[] 代码实现:
void f(int *a,int low,int high){
int l=low;
int h=high;
int p=a[low];
if(low<high){
while(low<high){
while(a[high]>=p&&low<high){
high--;
}
a[low]=a[high];
while(a[low]<=p&&low<high){
low++;
}
a[high]=a[low];
}
a[low]=p;
f(a,l,low-1);
f(a,low+1,h);
}
}
struct ListNode* sortList(struct ListNode* head){
struct ListNode* p=head;
int a[100000];
int size=0;
int i;
while(p){
a[size++]=p->val;
p=p->next;
}
f(a,0,size-1);
p=head;
i=0;
while(p){
p->val=a[i++];
p=p->next;
}
return head;
}
|