Clean (18 lines) solution


  • 0
    A
    /* reverse linked list from h to t, inclusive; 'prev' is the previous element */
    ListNode* reverseList(ListNode* prev, ListNode* h, ListNode* t) {
      if (prev == t) return t; // if we hit ending node
      ListNode * nxt = h->next;
      h->next = prev;
      return reverseList(h, nxt, t);
    }
    
    ListNode* reverseKGroup(ListNode* h, int k) {
      int i = 0;
      ListNode* p = h;
      while (p && i < k - 1) p= p->next, i++; // find current k nodes
    
      if (!p) return h; // if we are short of k nodes, then return head
      
      // recurse to get next node, which will be set as the next node
      // of current k-group
      ListNode* nxt = reverseKGroup(p->next, k);
    
      // reverse from h to p, inclusive
      ListNode* ret = reverseList(nxt, h, p);
      return ret;
    }
    

Log in to reply
 

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