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;
    }
};
相关推荐
Q***l68713 小时前
C++在计算机图形学中的渲染
开发语言·c++
稚辉君.MCA_P8_Java13 小时前
Gemini永久会员 Java动态规划
java·数据结构·leetcode·排序算法·动态规划
oioihoii13 小时前
C++语言演进之路:从“C with Classes”到现代编程基石
java·c语言·c++
小白程序员成长日记14 小时前
2025.11.23 力扣每日一题
算法·leetcode·职场和发展
咔咔咔的14 小时前
3190. 使所有元素都可以被 3 整除的最少操作数
c++
T***160714 小时前
C++在游戏开发中的AI行为树
开发语言·c++
自由生长202415 小时前
为什么C++项目偏爱.cxx扩展名:从MongoDB驱动说起
c++
CSDN_RTKLIB15 小时前
【GNU、GCC、g++、MinGW、MSVC】上
c++·gnu
b***748816 小时前
C++在系统中的内存对齐
开发语言·c++
散峰而望16 小时前
C++数组(三)(算法竞赛)
开发语言·c++·算法·github