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;
    }
};
相关推荐
_dindong4 分钟前
动规:01背包
数据结构·笔记·学习·算法·leetcode·动态规划·力扣
玖笙&12 分钟前
✨WPF编程基础【2.1】布局原则
c++·wpf·visual studio
玖笙&20 分钟前
✨WPF编程基础【2.2】:布局面板实战
c++·wpf·visual studio
菜鸡爱玩2 小时前
Qt3D--箭头示例
c++·qt
深思慎考3 小时前
【新版】Elasticsearch 8.15.2 完整安装流程(Linux国内镜像提速版)
java·linux·c++·elasticsearch·jenkins·框架
sxtyjty4 小时前
ABC426G - Range Knapsack Query
c++·算法·分治
hetao17338374 小时前
2025-10-03 HETAO CSP-S复赛集训营模拟赛-002 总结 Ⅱ
c++·总结
ajassi20004 小时前
开源 C++ QT QML 开发(四)复杂控件--Listview
c++·qt·开源
Vect__4 小时前
二叉树实战笔记:结构、遍历、接口与 OJ 实战
数据结构·c++·算法
青草地溪水旁5 小时前
第六章:适配器模式 - 接口转换的艺术大师
c++·适配器模式