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;
    }
};
相关推荐
Alfred king1 小时前
面试150 生命游戏
leetcode·游戏·面试·数组
水木兰亭2 小时前
数据结构之——树及树的存储
数据结构·c++·学习·算法
CoderCodingNo3 小时前
【GESP】C++四级考试大纲知识点梳理, (7) 排序算法基本概念
开发语言·c++·排序算法
秋风&萧瑟4 小时前
【C++】C++中的友元函数和友元类
c++
梁诚斌5 小时前
使用OpenSSL接口读取pem编码格式文件中的证书
开发语言·c++
薰衣草23338 小时前
一天两道力扣(1)
算法·leetcode·职场和发展
爱coding的橙子9 小时前
每日算法刷题Day41 6.28:leetcode前缀和2道题,用时1h20min(要加快)
算法·leetcode·职场和发展
2301_803554529 小时前
c++中的绑定器
开发语言·c++·算法
海棠蚀omo9 小时前
C++笔记-位图和布隆过滤器
开发语言·c++·笔记
消失的旧时光-19439 小时前
c++ 的标准库 --- std::
c++·jni