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;
    }
};
相关推荐
小开不是小可爱3 分钟前
leetcode_454. 四数相加 II_java
java·数据结构·算法·leetcode
aaaweiaaaaaa1 小时前
蓝桥杯c ++笔记(含算法 贪心+动态规划+dp+进制转化+便利等)
c语言·数据结构·c++·算法·贪心算法·蓝桥杯·动态规划
FreeLikeTheWind.1 小时前
Qt 开发时可以在函数内引用的头文件
开发语言·c++·qt
说码解字1 小时前
C++ 的右值引用和移动语义
c++
h^hh2 小时前
pipe匿名管道实操(Linux)
数据结构·c++·算法
岁ovo寒2 小时前
【无标题】
c++
亓才孓2 小时前
[leetcode]01背包问题
算法·leetcode·职场和发展
its_a_win3 小时前
蓝桥杯 2023省B 飞机降落 dfs
c++·算法·蓝桥杯
脑斧猴3 小时前
Linux中进程
linux·服务器·c++
tan180°4 小时前
Linux自行实现的一个Shell(15)
linux·服务器·c++·后端·vim