An easy-understanding solution


  • 0
    S
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            if (k == 1) {
                return head;
            }
            
            int cnt = 0;
            ListNode* node = head;
            while (node) {
                if (cnt == k-1) {
                    ListNode* next = node->next;
                    node->next = NULL;
                    ListNode* next_new = reverseKGroup(next, k);
                    
                    ListNode* newHead = reverse(head, next_new);
                    return newHead;            
                } else {
                    node = node->next;
                    cnt++;
                }            
            }
            return head;
        }
        
        ListNode* reverse(ListNode* head, ListNode* next) {
            /*
            // iterative
            ListNode* newHead;
            while (head) {
                ListNode* tmp = head->next;
                newHead = head;
                newHead->next = next;
                next = head;
                head = tmp;            
            }
            return newHead;        
            */
            
            // recursive
            if (!head) {
                return next;
            }
            
            ListNode* tmp = head->next;
            head->next = next;
            return reverse(tmp, head);
        }
    };
    

Log in to reply
 

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