leetcode 25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

递归法:

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(k==1)
            return head;
        ListNode* newHead = nullptr;
        ListNode* cur = head;
        int count = 0;
        while(cur && count < k){
            count++;
            newHead = cur;
            cur = cur->next;
        }
        if(count < k)
            return head;
        //到这里时,newHead是第k个结点,它将成为反转后的新的头结点
        ListNode* post = cur;//post是第k+1个结点

        ListNode* pre = nullptr; 
        cur = head;
        while(count--){
            ListNode* temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        head->next = reverseKGroup(post,k);//对第k+1个结点及其之后的结点递归处理

        return newHead;
    }
};

对比leetcode 92. Reverse Linked List II-CSDN博客

相关推荐
Hesionberger1 小时前
动态规划与二分法破解最长递增子序列
java·数据结构·python·算法·leetcode
令狐掌门2 小时前
2026华为OD面试题020:日志文件异常检测
算法·leetcode·华为od
To_OC11 小时前
LC 17 电话号码的字母组合:我的回溯算法,就是从这道题开窍的
javascript·算法·leetcode
海石18 小时前
【JS击败90%】前缀和+定长滑动窗口
算法·leetcode
Tisfy18 小时前
LeetCode 2685.统计完全连通分量的数量:DFS求每个连通块的边点数
算法·leetcode·深度优先··题解·连通图·全连通分量
海石19 小时前
1次遍历,空间复杂度击败100%,时间复杂度击败85%
算法·leetcode
lueluelue4719 小时前
LeetCode:滑动窗口
数据结构·算法·leetcode
青山木20 小时前
Hot 100 --- 二叉树与递归
java·数据结构·算法·leetcode·深度优先
tachibana21 天前
hot100 将有序数组转换为二叉搜索树(108)
java·数据结构·算法·leetcode
yh弓长1 天前
Redis的list类及基础指令
redis·list