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;
    }
};
相关推荐
祁思妙想1 分钟前
【LeetCode100】--- 1.两数之和【复习回滚】
数据结构·算法·leetcode
薰衣草23332 分钟前
一天两道力扣(2)
算法·leetcode
小鲈鱼-6 分钟前
【LeetCode4.寻找两个正序数组的中位数】二分O(log(m+n))
c++·算法
橘颂TA8 分钟前
【C++】红黑树的底层思想 and 大厂面试常问
数据结构·c++·算法·红黑树
chao_7899 分钟前
二分查找篇——寻找旋转排序数组中的最小值【LeetCode】
python·线性代数·算法·leetcode·矩阵
三体世界44 分钟前
TCP传输控制层协议深入理解
linux·服务器·开发语言·网络·c++·网络协议·tcp/ip
你的冰西瓜1 小时前
C++ 中最短路算法的详细介绍
c++·算法·图论·最短路
zstar-_1 小时前
【算法笔记】6.LeetCode-Hot100-链表专项
笔记·算法·leetcode
<但凡.1 小时前
数据结构与算法之美:广义表
数据结构·c++·算法
偷偷的卷3 小时前
【算法笔记 day three】滑动窗口(其他类型)
数据结构·笔记·python·学习·算法·leetcode