C++ recursive solution


  • 0
    H
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            ListNode sentinel(0);
            reverseKGroup(head, &sentinel, k);
            return sentinel.next;
        }
        void reverseKGroup(ListNode* head, ListNode* prev, int k){
             pair<ListNode*, ListNode*> ret = reverseOneKGroup(head, prev, k);
             if(ret.second != NULL){
                 reverseKGroup(ret.second, ret.first, k);
             }
        }
        pair<ListNode*, ListNode*> reverseOneKGroup(ListNode* head, ListNode* prev, int k){
                if(head == NULL){
                    return pair<ListNode*, ListNode*>(NULL, NULL);
                }
            if(k > 1){
                pair<ListNode*, ListNode*> ret = reverseOneKGroup(head->next, prev, k-1);
                if(ret.first == NULL){
                    prev->next = head;
                    return  pair<ListNode*, ListNode*>(NULL, NULL);
                }
                ret.first->next = head;
                head->next = NULL;
                ret.first = head;
                return  ret;
            } else {
                prev->next = head;
                ListNode* next = head->next;
                head->next = NULL;
                return  pair<ListNode*, ListNode*>(head, next);
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.