leetcode_148 Sort List

题目分析:

  • 对链表进行排序,要求时间复杂度为O(nlogn),常量空间。

解题思路:

  • 归并排序实现

    基本思想:找到链表的中间节点,然后递归对前半部分和后半部分分别进行归并排序,然后将两个排好序的链表进行合并即可。

    注意:如果数组进行归并排序,则空间不为常量空间。

  • 实现程序

    //找链表的中间节点
    struct ListNode *getMidList(struct ListNode *head)
    {
        if (head == NULL || head->next == NULL)
            return head;
        struct ListNode *p = head;
        struct ListNode *q = head;
        // 利用快慢指针查找中间节点 
        while (q != NULL && q->next != NULL && q->next->next != NULL)
        {
            p = p->next;
            q = q->next;
            q = q->next;
        }
        return p;
    }
    //两个链表的合并操作
    struct ListNode *mergeList(struct ListNode *a, struct ListNode *b)
    {
        struct ListNode *head = (struct ListNode *) malloc (sizeof(struct ListNode));
        struct ListNode *cur = head;
        while (a != NULL && b != NULL)
        {
            if (a->val <= b->val)
            {
                cur->next = a;
                a = a->next;
            }
            else
            {
                cur->next = b;
                b = b->next;
            }
            cur = cur->next;
        }
        cur->next = a != NULL ? a : b;
        return head->next;
    }
    // 对链表进行归并排序 
    struct ListNode *sortList(struct ListNode *head)
    {
        if (head == NULL || head->next == NULL)
            return head;
        // 获取中间及诶单 
        struct ListNode *mid = getMidList(head); 
        struct ListNode *next = mid->next;
        mid->next = NULL;
        // 对前半部分和后半部分递归进行归并排序 
        return mergeList(sortList(head), sortList(next));
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值