leetcode——148.排序链表

本文介绍了一种使用归并排序算法对链表进行排序的方法,通过递归拆分链表并在合并过程中保持升序,实现时间复杂度为O(nlogn),空间复杂度为O(n)。核心步骤包括链表中心查找和两个子链表的合并操作。

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

思路:

使用归并排序实现,时间复杂度为O(nlogn),空间负责为常数阶**O(n)**的算法

代码步骤:

  1. 一个用于链表中心查找,进行链表的递归分割;
  2. 一个用于对两个链表的合并,创建新表头,按序挑选元素;

代码实现:

class Solution {
public:
    ListNode* sortList(ListNode* head, ListNode* tail) {
        //链表为空
        if (head == nullptr) 
            return head;
        //链表只有一个元素——递归终止条件
        if (head->next == tail) {
            head->next = nullptr;
            return head;
        }
        //利用双指针(快慢指针)查找链表中点
        ListNode* slow = head, *fast = head;
        while (fast != tail) {
            slow = slow->next;
            fast = fast->next;
            if (fast != tail)
                fast = fast->next;
        }
        ListNode* mid = slow;
        //递归排序,合并子链表
        return merge(sortList(head, mid), sortList(mid, tail));
    }

    ListNode* merge(ListNode* head1, ListNode* head2) {
    	//创建一个新表头
        ListNode* Head_front = new ListNode(0);
        ListNode* temp = Head_front, *temp1 = head1, *temp2 = head2;
        //对比两个链表之间的值
        while (temp1 != nullptr && temp2 != nullptr) {
            if (temp1->val <= temp2->val) {
                temp->next = temp1;
                temp1 = temp1->next;
            }
            else {
                temp->next = temp2;
                temp2 = temp2->next;
            }
            temp = temp->next;
        }
        //将剩余数据进行一次拼接
        temp->next=temp1==nullptr? temp2:temp1;
        return Head_front->next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值