C++ | Leetcode C++题解之第25题K个一组翻转链表

题目:

题解:

cpp 复制代码
class Solution {
public:
    // 翻转一个子链表,并且返回新的头与尾
    pair<ListNode*, ListNode*> myReverse(ListNode* head, ListNode* tail) {
        ListNode* prev = tail->next;
        ListNode* p = head;
        while (prev != tail) {
            ListNode* nex = p->next;
            p->next = prev;
            prev = p;
            p = nex;
        }
        return {tail, head};
    }

    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode* hair = new ListNode(0);
        hair->next = head;
        ListNode* pre = hair;

        while (head) {
            ListNode* tail = pre;
            // 查看剩余部分长度是否大于等于 k
            for (int i = 0; i < k; ++i) {
                tail = tail->next;
                if (!tail) {
                    return hair->next;
                }
            }
            ListNode* nex = tail->next;
            // 这里是 C++17 的写法,也可以写成
            // pair<ListNode*, ListNode*> result = myReverse(head, tail);
            // head = result.first;
            // tail = result.second;
            tie(head, tail) = myReverse(head, tail);
            // 把子链表重新接回原链表
            pre->next = head;
            tail->next = nex;
            pre = tail;
            head = tail->next;
        }

        return hair->next;
    }
};
相关推荐
cu1439 小时前
细谈IT65631的具体功能与其应用
c++·单片机·嵌入式硬件
幻智星科技9 小时前
Karatsuba与CSD优化FPGA大数乘法
c++·fpga开发·密码学
文丑颜不良啊9 小时前
LeetCode476~500题目解析
java·leetcode
flower9803239 小时前
C++消息总线软件开发框架AI重构版
c++·设计模式·架构
lengxuenong9 小时前
树状数组 · 信息学学习手册3-优化LIS
c++·学习·算法
fanfan_hongyun10 小时前
【UE5.1 创建C++文件】
c++·ue5
余额瞒着我当琳10 小时前
C++11,发展历史浅谈,初始化列表和对象初始化,右值引用和移动语义
java·开发语言·c++·算法
Tsuki_tl10 小时前
【优选算法:双指针】——复写零题解
java·c++·算法·leetcode·数组·双指针·复写零
程序猿编码11 小时前
不用 PyTorch!从零手写 C++ 深度学习框架,自动微分、CUDA、分布式一把搞定
c++·深度学习·大模型推理·自动微分
real_metrix11 小时前
【学习笔记】C/C++ 头文件自包含
c++·c·头文件·自包含