Java simple solution


  • 0
    R
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null){
            return null;
        }
        if(k<2){
            return head;
        }
        //when the length of the listNode less than K, we should return this list
        ListNode newHead = head;
        ListNode start=head;
        while(head.next!=null){
            ListNode end = start;
            for(int index=0; index<k-1;index++){
                end=end.next;
                if(end==null){
                    return newHead;
                }
            }
            if(newHead==head){
                newHead = reverse(start,end);
            }
            else{
                head.next = reverse(start,end);
            }
            head = start;
            start=start.next;
        }
        return newHead;
    }
    
    private ListNode reverse(ListNode head, ListNode end){
        ListNode pre = head;
        ListNode current = pre.next;
        while(current!=end){
            ListNode next = current.next;
            current.next = pre;
            pre=current;
            current=next;
        }
        head.next=end.next;
        end.next = pre;
        return end;
    }

Log in to reply
 

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