My simple accepted solution


  • -1
    S
    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode *temp1=head;
        if(head==NULL||k<=1)return head;
        ListNode *temp=head;
        ListNode *before=new ListNode(-111);
        int length=0;
        while(temp1!=NULL){
            length++;
            temp1=temp1->next;
            
        }
        int n=length/k;
        if(n<1)return head;
        ListNode *result=head;
        int i=1;
        while(i<k){
          result=result->next;
          i++;
        }
        
        
        int cou=0;
        int m=0;
        while(temp!=NULL&&cou<n){
            m=0;
             ListNode *te_temp=temp;
            ListNode *temp_ne=temp->next;
           ListNode *temp_ne_ne=temp->next->next;
            
            while(m<k-2){
                temp_ne->next=temp;
                temp=temp_ne;
                temp_ne=temp_ne_ne;
                temp_ne_ne=temp_ne->next;
                m++;
            }
            temp_ne->next=temp;
            
            if(before->val!=-111){
               before->next=temp_ne; 
            }
            before=te_temp;
           temp=temp_ne_ne;
           cou++;
        }
        
        if(temp!=NULL)before->next=temp;
        else
        before->next=NULL;
        return result;
        
        
        
    }

Log in to reply
 

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