[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;
}
相关推荐
用户6869161349012 小时前
哈希表实现指南:从原理到C++实践
数据结构·c++
大老板a13 小时前
c++五分钟搞定异步处理
c++
羑悻的小杀马特16 小时前
从信息孤岛到智能星云:学习助手编织高校学习生活的全维度互联网络
c++·学习·生活·api
C++ 老炮儿的技术栈17 小时前
VSCode -配置为中文界面
大数据·c语言·c++·ide·vscode·算法·编辑器
祁同伟.17 小时前
【C++】类和对象(上)
c++
90wunch17 小时前
更进一步深入的研究ObRegisterCallBack
c++·windows·安全
刃神太酷啦17 小时前
聚焦 string:C++ 文本处理的核心利器--《Hello C++ Wrold!》(10)--(C/C++)
java·c语言·c++·qt·算法·leetcode·github
DARLING Zero two♡17 小时前
C++数据的输入输出秘境:IO流
c++·stl·io流
知然2 天前
鸿蒙 Native API 的封装库 h2lib_arkbinder
c++·arkts·鸿蒙
十五年专注C++开发2 天前
Qt .pro配置gcc相关命令(三):-W1、-L、-rpath和-rpath-link
linux·运维·c++·qt·cmake·跨平台编译