[leetcode]148. 排序链表

本文介绍了一种在O(nlogn)时间复杂度和常数级空间复杂度下,使用归并排序对链表进行排序的方法。通过示例展示了如何将无序链表4->2->1->3排序为1->2->3->4,以及如何将-1->5->3->4->0排序为-1->0->3->4->5。文章详细解释了利用快慢指针寻找链表中点,并递归地对链表进行排序和合并的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4

示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法:
利用归并排序,进行排序。再求中间节点时利用,两个指针fast,slow,fast一次走两个节点而slow走一个节点,当fast走完整个链表时,slow正好处于中间节点上。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    ListNode* merge(ListNode* l1, ListNode*l2) {
        if (!l1) return l2;
        if (!l2) return l1;
        
        ListNode head(0);
        ListNode* opre = &head;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                opre->next = l1;
                opre = l1;
                l1 = l1->next;
            } else {
                opre->next = l2;
                opre = l2;
                l2 = l2->next;
            }   
        }
        
        opre->next = (l1 ? l1 : l2);
        return head.next;
    }

public:
    ListNode* sortList(ListNode* head) {
        if (!head || !head->next)
            return head;
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* pre = head;
        while (fast && fast->next) {
            fast = fast->next->next;
            pre = slow;
            slow = slow->next;
        }
        pre->next = nullptr;
        ListNode* L1 = sortList(head);
        ListNode* L2 = sortList(slow);
        return merge(L1, L2);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值