Share my recurive code ( quite easy to understand )


  • 0
    W
    class Solution {
    public:
        ListNode *reverseKGroup(ListNode *head, int k) {
            // if NULL
            if (head == NULL) return NULL;
            
            // if less than k nodes
            ListNode *p = head;
            for (int i = 1; i < k; ++i) {
                p = p->next;
                if (p == NULL) return head;
            }
            
            // reverse first k nodes
            ListNode *oldHead = head;
            for (int i = 1; i < k; ++i) {
                p = oldHead->next;
                if (p == NULL) return oldHead;
                oldHead->next = p->next;
                p->next = head;
                head = p;
            }
            
            // reverse remaining nodes
            oldHead->next = reverseKGroup(oldHead->next, k);
            
            return head;
        }
    };

Log in to reply
 

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