[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;
}
相关推荐
招摇的一半月亮4 小时前
P2242 公路维修问题
数据结构·c++·算法
f***01935 小时前
CC++链接数据库(MySQL)超级详细指南
c语言·数据库·c++
合方圆~小文6 小时前
球型摄像机作为现代监控系统的核心设备
java·数据库·c++·人工智能
椰萝Yerosius7 小时前
[题解]2024CCPC郑州站——Z-order Curve
c++·算法
滨HI010 小时前
C++ opencv简化轮廓
开发语言·c++·opencv
学习路上_write10 小时前
FREERTOS_互斥量_创建和使用
c语言·开发语言·c++·stm32·单片机·嵌入式硬件
闻缺陷则喜何志丹11 小时前
【SOSDP模板 容斥原理 逆向思考】3757. 有效子序列的数量|分数未知
c++·算法·力扣·容斥原理·sosdp·逆向思考
BestOrNothing_201511 小时前
一篇搞懂 C++ 重载:函数重载 + 运算符重载,从入门到会用(含 ++、<<、== 实战)
c++·函数重载·运算符重载·operator·前置后置++·重载与重写
2501_9411444212 小时前
Python + C++ 异构微服务设计与优化
c++·python·微服务
程序猿编码12 小时前
PRINCE算法的密码生成器:原理与设计思路(C/C++代码实现)
c语言·网络·c++·算法·安全·prince