My simple 24ms C++ solution using recursion


  • 0
    T
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            if(k<=1)
                return head;
                
            if(head==NULL || head->next == NULL)
                return head;
                
            ListNode* p = head;
            int n = 1;
            while(p->next)
            {
                p = p->next;
                n = n + 1;
                if(n==k)
                    break;
            }
            
            if(n<k)
                return head;
            
            ListNode* nextHead = reverseKGroup(p->next, k);
            p->next = NULL;
            
            ListNode* next = head->next;
            head->next = NULL;
            ListNode* current = head;
            while(next)
            {
                ListNode* tmp = next->next;
                next->next = current;
                current = next;
                next = tmp;
            }
            
            head->next = nextHead;
            
            return current;
        }
    };

Log in to reply
 

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