[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;
}
相关推荐
天若有情67319 分钟前
我发明的PROTO_V4协议:一个让数据“穿上迷彩服”的发明(整数传输协议)
网络·c++·后端·安全·密码学·密码·数据
加油=^_^=20 分钟前
【C++11】特殊类设计 | 类型转换
c++·单例模式·类型转换
加成BUFF23 分钟前
C++入门详解2:数据类型、运算符与表达式
c语言·c++·计算机
徐行code26 分钟前
std::bind()和lambda的区别
c++
小老鼠不吃猫41 分钟前
C++20 STL <numbers> 数学常量库
开发语言·c++·c++20
程序员zgh1 小时前
C++常用设计模式
c语言·数据结构·c++·设计模式
im_AMBER1 小时前
Leetcode 80 统计一个数组中好对子的数目
数据结构·c++·笔记·学习·算法·leetcode
尘诞辰1 小时前
【C语言】数据在内存中的储存
c语言·开发语言·数据结构·c++
无敌最俊朗@1 小时前
STL-关联容器(面试复习4)
开发语言·c++
无限进步_1 小时前
【C语言】栈(Stack)数据结构的实现与应用
c语言·开发语言·数据结构·c++·后端·visual studio