Sort a linked list in O(n log n) time using constant space complexity.
题目要求:以O(n log n)的时间复杂度,排序链表
第一反应就是先读出链表中的数字于数组中,调用O(n log n)的算法进行排序,最后组装成链表返回结果
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
#define leftchild(x) (2*(x)+1)
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
void shift(int v[],int i,int n)
{
int child;
int temp;
for(temp=v[i];leftchild(i)<n;i=child)
{
child=leftchild(i);
if(child!=n-1&&v[child+1]>v[child])
child++;
if(v[child]>temp)
v[i]=v[child];
else
break;
}
v[i]=temp;
}
void heap_sort(int v[],int n)
{
int i,j;
for(i=n/2;i>=0;i--)
shift(v,i,n);
for(j=n-1;j>0;j--)
{
swap(&v[0],&v[j]);
shift(v,0,j);
}
}
ListNode *sortList(ListNode *head) {
int arr[100000];
int count=0;
ListNode * cur=head;
while(cur!=NULL)
{
arr[count++]=cur->val;
cur=cur->next;
}
heap_sort(arr,count);
ListNode *res=NULL;
for(int i=count-1;i>=0;i--)
{
if(res==NULL)
{
res=(ListNode*)malloc(sizeof(ListNode));
res->next=NULL;
res->val=arr[i];
}
else
{
ListNode *temp=(ListNode*)malloc(sizeof(ListNode));
temp->val=arr[i];
temp->next=res;
res=temp;
}
}
return res;
}
};