Solution with C++ which is really easy to understand


  • -2
    Z
    ListNode* reverseKGroup(ListNode* head, int k)
    {     
     ListNode *p = head, *tmp = head;
     int m = 0, cnt = 0;
    
     while (tmp != NULL) {++cnt; tmp = tmp->next;}
     tmp = head;
     ListNode *q = tmp;
    
     while (tmp != NULL) {
          if (cnt-m < k) break;
          int arr[k];
          for (int i = 0; i < k; ++i) {
               arr[i] = q->val;
               q = q->next;
               ++m;
          }
          for (int i = k-1; i >= 0; --i) {
               tmp->val = arr[i];
               tmp = tmp->next;
          }
     }
    
     return p;
    }

Log in to reply
 

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