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;
    }
};
相关推荐
Sashtok2 小时前
cpp基础知识(10)
c++·后端
whitelbwwww3 小时前
CUDA C++实战--中级
开发语言·前端·c++
ShineWinsu6 小时前
对于Qt:QMessageBox的解析
开发语言·c++·qt·面试·客户端·qmessagebox·消息对话框
小灰灰搞电子9 小时前
C++ initializer_list 详解
c++·list
Rabitebla11 小时前
【Linux】文件篇(六):Shell 实战——从系统调用到命令行重定向
linux·服务器·c++·笔记·学习
Pniubi21 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
无忧.芙桃1 天前
C++语言原理与实践(二十三):哈希表的实现
c++·链表·哈希算法·散列表·哈希表
文丑颜不良啊1 天前
LeetCode3401~3420题目解析
java·leetcode
AvocadoZeroOneOI1 天前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊1 天前
LeetCode3421~3440题目解析
java·leetcode