BM12 单链表的排序
给定一个节点数为n的无序单链表,对其按升序排序。
数据范围:0<n≤100000,保证节点权值在[-10^9,10^9]之内。
要求:空间复杂度 O(n),时间复杂度 O(nlogn)
解法( 链表归并+数组归并+数组快排)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
#include <stdlib.h>
#include <string.h>
typedef struct ListNode* pnode;
/*
static void inner_sort_arr(int val[] , int le , int ri)
{
if(le==ri)return;
if(le+1==ri)
{
if(val[le]>val[ri])
{
val[le] ^= val[ri];
val[ri] ^= val[le];
val[le] ^= val[ri];
}
return ;
}
int mid = (le+ri)>>1;
inner_sort_arr(val, le, mid);
inner_sort_arr(val, mid+1, ri);
int *tmp = malloc(sizeof(int)*(ri-le+1));
int le_i = le;
int ri_i = mid+1;
int i = 0;
while(le_i<=mid&&ri_i<=ri)
{
if(val[le_i]<=val[ri_i])
{
tmp[i++] = val[le_i++];
}else {
tmp[i++] = val[ri_i++];
}
}
while (le_i<=mid) {
tmp[i++] = val[le_i++];
}
while (ri_i<=ri) {
tmp[i++] = val[ri_i++];
}
memcpy(val+le , tmp , sizeof(int)*(ri-le+1));
free(tmp);
}
static pnode sort_inner(pnode le , pnode ri, int plen )
{
if(plen==1)
{
le->next = NULL;
return le;
}
if(plen==2)
{
if(le->val<=ri->val){
ri->next = NULL;
return le;
}
ri->next = le ;
le->next=NULL;
return ri;
}
int mid = plen>>1;
pnode head =le;
while(--mid)
{
head=head->next;
}
mid = plen>>1;
pnode rhead = sort_inner(head->next, ri, plen-mid);
head->next = NULL;
pnode lhead = sort_inner(le, head, plen>>1);
lhead->val<rhead->val?(head=lhead,lhead=lhead->next):(head=rhead,rhead=rhead->next);
le=head;
while(lhead&&rhead)
{
if(lhead->val<=rhead->val)
{
head->next = lhead;
lhead = lhead->next;
}else{
head->next = rhead;
rhead = rhead->next;
}
head = head->next;
}
head->next = lhead?lhead:rhead;
return le;
}
*/
static int qsort_fnc(const void* a ,const void* b)
{
return *(int*)a-*(int*)b;
}
struct ListNode* sortInList(struct ListNode* head ) {
// write code here
if(!head||head->next==NULL)return head;
int plen = 1;
int val[100000];
pnode p = head, p_next=head->next;
while(p_next)
{
val[plen-1]=p->val;
plen++;
p = p_next;
p_next = p_next->next;
}
val[plen-1]=p->val;
p = head;
//inner_sort_arr(val , 0 ,plen-1);
qsort(val, plen, sizeof(int), qsort_fnc);
plen = 0;
while(p)
{
p->val = val[plen++];
p=p->next;
}
return head;
//return sort_inner(head, p, plen); // answer 1
}