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

相关推荐
编程绿豆侠8 分钟前
力扣HOT100之技巧:75. 颜色分类
算法·leetcode·排序算法
Lenyiin1 小时前
第 87 场周赛:比较含退格的字符串、数组中的最长山脉、一手顺子、访问所有节点的最短路径
java·c++·python·leetcode·周赛·lenyiin
云边小网安4 小时前
分析 java 的 Map<String,Map<String, List<Map<String,Integer>>>>
java·开发语言·list
怀旧,12 小时前
【数据结构】5. 双向链表
数据结构·windows·链表
Once_day13 小时前
代码训练LeetCode(29)最后一个单词的长度
算法·leetcode·c
凌肖战13 小时前
力扣上C语言编程题:最大子数组和(涉及数组)
c语言·算法·leetcode
蒟蒻小袁13 小时前
力扣面试150题--除法求值
算法·leetcode·面试
客卿12313 小时前
力扣hot100--反转链表
算法·leetcode·链表
zhuiQiuMX13 小时前
力扣LFU460
python·leetcode