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;
    }
};
相关推荐
oem1106 小时前
C++中的享元模式实战
开发语言·c++·算法
casual~7 小时前
第?个质数(埃氏筛算法)
数据结构·c++·算法
Elnaij7 小时前
从C++开始的编程生活(20)——AVL树
开发语言·c++
hanbr7 小时前
【C++ STL核心】vector:最常用的动态数组容器(第九天核心)
开发语言·c++
仰泳的熊猫8 小时前
题目2308:蓝桥杯2019年第十届省赛真题-旋转
数据结构·c++·算法·蓝桥杯
lzksword9 小时前
C++ Builder XE OpenDialog1打开多文件并显示xls与xlsx二种格式文件
java·前端·c++
niceffking9 小时前
C++内部类的ISO约定和语法细节
开发语言·c++
IronMurphy9 小时前
【算法二十六】108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
数据结构·算法·leetcode
im_AMBER10 小时前
Leetcode 141 最长公共前缀 | 罗马数字转整数
算法·leetcode
艾莉丝努力练剑10 小时前
【脉脉】AI创作者崛起:掌握核心工具,在AMA互动中共同成长
运维·服务器·c++·人工智能·安全·企业·脉脉