simple C++, < 20 lines, 19ms


  • 0
    S
        ListNode* reverseKGroup(ListNode* head, int k) {
            if(head == NULL)return head;
            if(head->next == NULL)return head;
            ListNode* cur=head;
            vector<ListNode*> tmp;
            while(cur != NULL){tmp.push_back(cur); cur = cur->next;}
            int n = tmp.size()/k;
            if(n==0)return head;
            for(int i = 1; i<=n; i++){
                cur = tmp[i*k-k];
                for(int m=1; m<=k; m++){
                    tmp[i*k-m] = cur;
                    cur = cur->next;
                }
            }
            for(int i=0; i<tmp.size()-1; i++){tmp[i]->next = tmp[i+1];}
            tmp[tmp.size()-1]->next = NULL;
            head = tmp[0];
            return head;
        }
    
    

Log in to reply
 

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