Leetcode--Sort List

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;
        
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值