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

相关推荐
xiaopengbc1 小时前
谷歌商店下载APK教程,先下载谷歌三件套,再直接从 Google Play 下载 APK 文件?
leetcode
逐步前行3 小时前
C数据结构--线性表(顺序表|单链表|双向链表)
c语言·数据结构·链表
spencer_tseng5 小时前
JDK 9 List.of(...)
java·windows·list·1024程序员节
Dream it possible!6 小时前
LeetCode 面试经典 150_链表_反转链表 II(60_92_C++_中等)(头插法)
c++·leetcode·链表·面试
py有趣8 小时前
LeetCode学习之实现strStr()
学习·算法·leetcode
夏鹏今天学习了吗8 小时前
【LeetCode热题100(52/100)】课程表
算法·leetcode·职场和发展
祁思妙想8 小时前
【LeetCode100】--- 101.重排链表【思维导图+复习回顾】
算法·leetcode·链表
Dream it possible!8 小时前
LeetCode 面试经典 150_链表_随机链表的复制(59_138_C++_中等)
c++·leetcode·链表
胡萝卜3.017 小时前
C++ list核心接口与实战技巧
数据结构·c++·list·list使用
Dream it possible!17 小时前
LeetCode 面试经典 150_链表_合并两个有序链表(58_21_C++_简单)
leetcode·链表·面试·1024程序员节