My simple c++ code 28ms easy to understand


  • 0
    L
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) 
        {
             if(!head||head->next==nullptr||k<2)return head;
             ListNode *cur=head,*pre=nullptr,*next=nullptr;
             
             while(find_kth(cur,k))
             {
                 next=find_kth(cur,k)->next;
                 cur=reverseList(cur,k);
                 if(!pre)head=cur;
                 else
                 pre->next=cur;
                 pre=find_kth(cur,k);
                 cur=next;
                 if(!find_kth(cur,k))pre->next=next;
             }
             return head;
            
        }
        
    private:
        ListNode* reverseList(ListNode *head,int k) //reverse k nodes
        {
           if(head==nullptr)return head;
           ListNode* endk=find_kth(head,k);
           if(!endk)return head;
           endk->next=nullptr;
           ListNode *cur=head,*next=head->next,*pre=nullptr;
           while(next!=nullptr)
           {
               cur->next=pre;
               pre=cur;
               cur=next;
               next=cur->next;
           }
           cur->next=pre;
           return cur;
        }
        ListNode* find_kth(ListNode* cur,int k)
        {
             if(!cur)return nullptr;
            while(--k)
            {
                cur=cur->next;
                if(!cur)return nullptr;
            }
            return cur;
        }
        
      
    };

Log in to reply
 

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