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博客

相关推荐
x_xbx7 小时前
LeetCode:34. 在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
愣头不青11 小时前
96.不同的二叉搜索树
数据结构·算法·leetcode
alphaTao13 小时前
LeetCode 每日一题 2026/3/23-2026/3/29
服务器·windows·leetcode
Sirens.13 小时前
对顺序表以及双向链表的理解
数据结构·链表
不光头强14 小时前
力扣78子集题解
算法·leetcode·深度优先
Magic--14 小时前
经典概率题:飞机座位分配问题(LeetCode 1227)超详细解析
算法·leetcode·职场和发展
We་ct15 小时前
LeetCode 4. 寻找两个正序数组的中位数:二分优化思路详解
前端·数据结构·算法·leetcode·typescript·二分
滴滴答滴答答17 小时前
LeetCode Hot100 之 41 缺失的第一个正数
算法·leetcode·职场和发展
Sakinol#17 小时前
Leetcode Hot 100 ——多维动态规划
算法·leetcode·动态规划
xsyaaaan17 小时前
leetcode-hot100-二叉树
数据结构·leetcode