Recursive c++ solution


  • 0
    U
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            if ( head == NULL || k == 1) {
                return head;
            }
            ListNode *begin = head;
            ListNode *end = head;
            int i = 1;
            while (i < k && end != NULL) {
                end = end->next;
                i++;
            }
            if ( end == NULL ) {
                return head;
            }
            ListNode *current = begin->next;
            ListNode *prev = begin;
            begin->next = reverseKGroup(end->next, k);
            while (current != end) {
                ListNode *future = current->next;
                current->next = prev;
                prev = current;
                current = future;
            }
            end->next = prev;
            return end;
        }
    };
    

Log in to reply
 

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