15 lines C++ solution using two second rank pointers


  • 0
    X
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            ListNode **pp1 = &head, **pp2 = &(head->next), *tmp;
            int num = 0;
            for(tmp=head; tmp; num++) tmp=tmp->next;
            while(num>=k) {
                for(int i=1; i<k; i++) {
                    tmp = *pp2;
                    *pp2 = tmp->next;
                    tmp->next = *pp1;
                    *pp1 = tmp;
                }
                pp1 = pp2;
                pp2 = &((*pp2)->next);
                num -= k;
            }
            return head;
        }
    };
    

Log in to reply
 

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