C++ 19ms


  • 0
    F
      class Solution {
    public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(head == NULL || head->next == NULL)
        {
            return head;
        }
        ListNode* phead = head;
        ListNode* qhead = head;
        ListNode* next;
        ListNode* pre = head;
        int n;
    
        while(qhead != NULL)
        {
             n = k-1;
    
            while(n > 0)
            {
             phead = phead->next;
             if(phead == NULL)
             {
                 return head;
             }
             n--;
            }
    
            next = phead->next;
            phead->next = NULL;
            phead = reserve(qhead);
    
            if(qhead == head)
            {
                head = phead;
            }
            pre->next = phead;
            pre = qhead;
            qhead->next = next;
            qhead = qhead->next;
            phead = qhead;
        }
    
        return head;
    }

Log in to reply
 

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