A simple and easy understand c++ solution 19ms


  • 0
    S

    Just put each group's value to a stack and keep one pointer p to each header of group. And for each group just pop the int value and replace the original value with that value! that's it ~

    ListNode* reverseKGroup(ListNode* head, int k) {
            ListNode * result = head;
    
            int a[k];
            int i = 0;
            ListNode *p = head;
            while (head) {
                if (i != k)
                {
                    a[i++] = head->val;
                    head = head->next;
                }
                if (i == k)
                {
                    while (p != head) {
                        p->val = a[--i];
                        p = p->next;
                    }
                }
            }
            return result;
        }
    

Log in to reply
 

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