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

相关推荐
重庆小透明17 分钟前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq36 分钟前
力扣:70. 爬楼梯
算法·leetcode·职场和发展
岁忧2 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
??tobenewyorker4 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
oioihoii5 小时前
C++11 forward_list 从基础到精通:原理、实践与性能优化
c++·性能优化·list
凌肖战7 小时前
力扣网C语言编程题:快慢指针来解决 “寻找重复数”
c语言·算法·leetcode
让我们一起加油好吗10 小时前
【C++】list 简介与模拟实现(详解)
开发语言·c++·visualstudio·stl·list
Vitta_U10 小时前
MFC的List Control自适应主界面大小
c++·list·mfc
Alfred king20 小时前
面试150 生命游戏
leetcode·游戏·面试·数组
醇醛酸醚酮酯1 天前
基于多线程实现链表快排
数据结构·链表