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;
    }
};
相关推荐
神仙别闹21 小时前
基于QT(C++)实现学本科教务系统(URP系统)
数据库·c++·qt
deng-c-f21 小时前
Linux C/C++ 学习日记(49):线程池
c++·学习·线程池
ulias21221 小时前
C++ 的容器适配器——从stack/queue看
开发语言·c++
daidaidaiyu1 天前
FFmpeg 关键的结构体
c++·ffmpeg
欧特克_Glodon1 天前
C++医学图像处理经典ITK库用法详解<一>:图像输入输出模块功能
c++·图像处理·itk
一个不知名程序员www1 天前
算法学习入门---priority_queue(C++)
c++·算法
LYFlied1 天前
【每日算法】LeetCode 84. 柱状图中最大的矩形
前端·算法·leetcode·面试·职场和发展
Pafey1 天前
C++的左值引用、右值引用以及转发和完美转发
c++
CoderCodingNo1 天前
【GESP】C++三级真题 luogu-B4414 [GESP202509 三级] 日历制作
开发语言·c++·算法
晨曦夜月1 天前
笔试强训day7
开发语言·c++·算法