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;
    }
};
相关推荐
And_Ii29 分钟前
LeetCode 3397. 执行操作后不同元素的最大数量
数据结构·算法·leetcode
。TAT。29 分钟前
C++ - List
数据结构·c++·学习
额呃呃35 分钟前
leetCode第33题
数据结构·算法·leetcode
dragoooon341 小时前
[优选算法专题四.前缀和——NO.27 寻找数组的中心下标]
数据结构·算法·leetcode
小龙报1 小时前
《算法通关指南---C++编程篇(2)》
c语言·开发语言·数据结构·c++·程序人生·算法·学习方法
王夏奇2 小时前
C++友元函数和友元类!
开发语言·c++
xzal123 小时前
C++之理解共用体
c++
_OP_CHEN3 小时前
C++基础:(十六)priority_queue和deque的深度解析
开发语言·c++
C++ 老炮儿的技术栈3 小时前
include″″与includ<>的区别
c语言·开发语言·c++·算法·visual studio
BS_Li3 小时前
C++IO库
c++·io流