【链表 - LeetCode】25. K 个一组翻转链表

25. K 个一组翻转链表 - 力扣(LeetCode)

题解

递归解法

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (head == nullptr) return nullptr;
        ListNode* prev = head;
        ListNode* index = head->next;
        int m = 0;
        // 考虑每k个情况,单链表反转
        while (++m < k && index != nullptr) {
            prev->next = index->next;
            index->next = head;
            head = index;
            index = prev->next;
        }
        if (m < k) {
            return reverseKGroup(head, m);
        }
        // 注意这里是index,即下一组的头
        prev->next = reverseKGroup(index, k);
        return head;
    }
};

迭代

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
       ListNode* dummy = new ListNode(0, head);
       ListNode* prev = dummy;
       ListNode* cur = head;
       int n = 0; // 链表长度
       while(cur != nullptr){
            n ++;
            cur = cur->next;
       }
       n = n / k;
       cur = head;
       for(int i = 1; i <= n *(k-1); i++){
            ListNode* nxt = cur->next;
            cur->next = nxt->next;
            nxt->next = prev->next;
            prev->next = nxt;
            if(i % (k-1) == 0){
                prev = cur;
                cur = cur->next;
            }
       }
       return dummy->next;
    }
};
相关推荐
2301_8002561123 分钟前
B+树:数据库的基石 R树:空间数据的索引专家 四叉树:空间划分的网格大师
数据结构·数据库·b树·机器学习·postgresql·r-tree
独自破碎E23 分钟前
【队列】按之字形顺序打印二叉树
leetcode
码农幻想梦29 分钟前
第九章 高级数据结构
数据结构
AlenTech30 分钟前
206. 反转链表 - 力扣(LeetCode)
数据结构·leetcode·链表
踩坑记录30 分钟前
leetcode hot100 438. 找到字符串中所有字母异位词 滑动窗口 medium
leetcode·职场和发展
大厂技术总监下海1 小时前
用户行为分析怎么做?ClickHouse + 嵌套数据结构,轻松处理复杂事件
大数据·数据结构·数据库
YuTaoShao1 小时前
【LeetCode 每日一题】1458. 两个子序列的最大点积——(解法三)状态压缩
算法·leetcode·职场和发展
AI科技星1 小时前
光速飞行器动力学方程的第一性原理推导、验证与范式革命
数据结构·人工智能·线性代数·算法·机器学习·概率论
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——leetCode 946 题:验证栈序列
c++·算法·leetcode·职场和发展·结构与算法