[C/C++] List相关操作

List相关操作

1 链表二分

目标:

(1)对于偶数节点,正好对半分;

(2)对于奇数节点,前 = 后 + 1

(3)断开链表,方便后期合并

cpp 复制代码
// 使用快慢指针完成中点拆分
ListNode *SplitList(ListNode *head) {
    ListNode *slow{head};
    ListNode *fast{head};

    while (fast->next != nullptr && fast->next->next != nullptr) {
        slow = slow->next;
        fast = fast->next->next;
    }

    ListNode *mid = slow->next;
    slow->next = nullptr;
    return mid;
}

2 链表合并

cpp 复制代码
ListNode *MergeList(ListNode *head1, ListNode *head2) {
    ListNode dummy{};
    ListNode *cur = &dummy;

    while (head1 != nullptr && head2 != nullptr) {
        if (head1->val < head2->val) {
            cur->next = head1;
            head1 = head1->next;
        } else {
            cur->next = head2;
            head2 = head2->next;
        }

        cur = cur->next;
    }


    cur->next = (head1 != nullptr) ? head1 : head2;
    return dummy.next;
}

3 链表排序

cpp 复制代码
ListNode* sortList(ListNode* head) {
    // 题目进阶要求 nlgn => 希尔/归并/快速/堆
    if (head == nullptr || head->next == nullptr) {
        return head;
    }

    ListNode *head2 = SplitList(head);

    head = sortList(head);
    head2 = sortList(head2);

    return MergeList(head, head2);
}

4 多链表合并

cpp 复制代码
ListNode* mergeKLists(vector<ListNode*>& lists) {
    auto cmp = [](const ListNode *lhs, const ListNode *rhs) {
        return lhs->val > rhs->val;
    };

	// 通过优先级队列进行排序,并将取出的后续节点继续插入
    priority_queue<ListNode *, vector<ListNode *>, decltype(cmp)> pq{};

    for (auto head : lists) {
        if (head != nullptr) {
            pq.push(head);
        }
    }

    ListNode dummy{};
    ListNode *cur = &dummy;

    while (!pq.empty()) {
        // 取最小
        ListNode *node = pq.top();
        pq.pop();

        if (node->next != nullptr) {
            pq.push(node->next);
        }

        cur->next = node;
        cur = node;
    }

    return dummy.next;
}
相关推荐
计算机安禾13 分钟前
【数据结构与算法】第4篇:算法效率衡量:时间复杂度和空间复杂度
java·c语言·开发语言·数据结构·c++·算法·visual studio
m0_4886333214 分钟前
C++与C语言的区别和联系,及其在不同领域的应用分析
c语言·c++·面向对象·嵌入式系统·系统软件
Oueii19 分钟前
嵌入式LinuxC++开发
开发语言·c++·算法
sw12138920 分钟前
嵌入式C++驱动开发
开发语言·c++·算法
初圣魔门首席弟子21 分钟前
bug2026.03.24
c++·bug
2501_9249526922 分钟前
C++中的适配器模式
开发语言·c++·算法
良木生香26 分钟前
【C++初阶】:C++类和对象(中):类的默认成员函数---万字解说(最主要的四点)
c语言·开发语言·c++
txinyu的博客27 分钟前
解析muduo源码之 TcpServer.h & TcpServer.cc
c++
☆56628 分钟前
C++安全编程指南
开发语言·c++·算法
星轨初途33 分钟前
类和对象(中):六大默认成员函数与运算符重载全解析
开发语言·c++·经验分享·笔记·ajax·servlet