Recrusive solution


  • 0
    M

    //method

    public ListNode reverseKGroup(ListNode head, int k) {

        if(head==null || head.next==null ||k==1)
        return head;
        
        
       head=reverseList2(head,k,head);
       return head;
       
        
    }
    public static ListNode reverseList2(ListNode head,int k,ListNode prev){
        
        ListNode headcopy=head;
        int j=0;
        while(headcopy!=null && j<k){
            headcopy=headcopy.next;
            j++;
            
        }
        if(j!=k)
        return head;
        ListNode current=head;
        
        ListNode future=current.next;
        current.next=reverseList2(headcopy,k,headcopy);
        current=future;
        while(current!=headcopy){
          future=current.next;
          current.next=prev;
          prev=current;
          current=future;
            
        }
        return prev;
        
    }

Log in to reply
 

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