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;
    }
};
相关推荐
TracyCoder1234 分钟前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
浒畔居6 分钟前
泛型编程与STL设计思想
开发语言·c++·算法
Fcy64813 分钟前
C++ 异常详解
开发语言·c++·异常
机器视觉知识推荐、就业指导32 分钟前
Qt 和 C++,是不是应该叫 Q++ 了?
开发语言·c++·qt
liu****1 小时前
三.Qt图形界面开发完全指南:从入门到掌握常用控件
开发语言·c++·qt
放荡不羁的野指针1 小时前
leetcode150题-滑动窗口
数据结构·算法·leetcode
小龙报1 小时前
【C语言进阶数据结构与算法】单链表综合练习:1.删除链表中等于给定值 val 的所有节点 2.反转链表 3.链表中间节点
c语言·开发语言·数据结构·c++·算法·链表·visual studio
EmbedLinX1 小时前
Linux之内存管理
linux·服务器·c语言·c++
南岩亦凛汀2 小时前
快速上手Ultimate++的编译链接和配置
c++·gui·开源框架
TracyCoder1232 小时前
LeetCode Hot100(13/100)——238. 除了自身以外数组的乘积
算法·leetcode