[leetcode]Reverse Nodes in k-Group

又是链表题,最近都不想做了。。。不过今天状态不好,做做吧

把链表分成大小为k的各种块,然后反转这些块。

想想还是有点麻烦的感觉。。。。

要考虑前面,后面的。。。。

那就递归吧。。。这应该就简单了。。。

就处理当前k个就好了。。。

找到这k个。。。reverse。。。

next指向后面处理好的head(递归

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode* head){
        ListNode* prev = nullptr;
        ListNode* nowNode = head;
        while(nowNode){
            ListNode* next = nowNode -> next;
            nowNode -> next =  prev;
            prev = nowNode;
            nowNode = next;
        }
        return prev;
    }
    ListNode *reverseKGroup(ListNode *head, int k) {
        if(head == nullptr || head -> next == nullptr || k < 2) return head;
        
        int cnt = 1;
        ListNode* nowHead = head;
        ListNode* nowNode = head;
        while(nowNode && cnt < k){
            cnt ++;
            nowNode = nowNode -> next;
        }
        if(nowNode && cnt == k){
            ListNode* tail = reverseKGroup(nowNode -> next , k);
            nowNode -> next = nullptr;
            head = reverse(head);
            nowHead -> next = tail;
        }
        return head;
    }
};
原文地址:https://www.cnblogs.com/x1957/p/3505415.html