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;
    }
};
相关推荐
oioihoii21 分钟前
构造函数和析构函数中的多态陷阱:C++的隐秘角落
java·开发语言·c++
bestadc1 小时前
LeetCode 几道 Promises 和 Time 的题目
javascript·算法·leetcode
墨染点香1 小时前
LeetCode 刷题【71. 简化路径】
算法·leetcode·职场和发展
名誉寒冰1 小时前
LeetCode 24 两两交换链表中的节点( 迭代与递归)
算法·leetcode·链表
小欣加油2 小时前
leetcode LCR 170.交易逆序对的总数
数据结构·c++·算法·leetcode·职场和发展·排序算法
focksorCr2 小时前
编译缓存工具 sccache 效果对比
c++·缓存·rust
木尼1232 小时前
leedcode 算法刷题第三十一天
算法·leetcode·职场和发展
长安——归故李2 小时前
【modbus学习】
java·c语言·c++·学习·算法·c#
索迪迈科技2 小时前
STL库——map/set(类函数学习)
开发语言·c++·学习
Dfreedom.3 小时前
在Windows上搭建GPU版本PyTorch运行环境的详细步骤
c++·人工智能·pytorch·python·深度学习