C++ O(n) recursive, without helper functions


  • 1
    X
    class Solution {
    public:
        
        ListNode* reverseKGroup(ListNode* head, int k) {
            if (!head || !head->next || k == 1) return head;
            
            ListNode *r, *p, *q;
            int i = 1;
            p = head->next;
            r = head;
            
            while (p && i < k) {
                q = p->next;
                p->next = r;
                r = p;
                p = q;
                i++;
            }
        
            if (i < k) {
                head->next = NULL;
                return reverseKGroup(r, i);
            } else {
                head->next = reverseKGroup(p, k);
                return r;
            }
        }
    };

Log in to reply
 

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