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

相关推荐
不知名XL15 分钟前
day50 单调栈
数据结构·算法·leetcode
@––––––30 分钟前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
YuTaoShao2 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
TracyCoder1233 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
季明洵3 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
only-qi3 小时前
leetcode19. 删除链表的倒数第N个节点
数据结构·链表
望舒5134 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
铉铉这波能秀5 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.5 小时前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
铉铉这波能秀5 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple