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

相关推荐
文丑颜不良啊5 小时前
LeetCode2981~3000题目解析
java·leetcode
文丑颜不良啊11 小时前
LeetCode3001~3020题目解析
java·leetcode
Pniubi19 小时前
力扣19 . 删除表的倒数第N个节点(栈)
算法·leetcode·职场和发展
文丑颜不良啊1 天前
LeetCode2761~2780题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2841~2860题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2921~2940题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2901~2920题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2861~2880题目解析
java·leetcode
文丑颜不良啊3 天前
LeetCode2821~2840题目解析
java·leetcode
Pniubi3 天前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表