Java 1ms recursive solution.


  • 0
    public ListNode reverseKGroup(ListNode head, int k) {
        if(k<=1||head==null||head.next==null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        reverselist(dummy,k);
        return dummy.next;
    }
    
    public void reverselist(ListNode lastend, int k){
        if(lastend==null||lastend.next==null) return;
        //check if there is enough nodes left
        ListNode curr = lastend.next;
        int count = 1;
        while(curr.next!=null){
            curr = curr.next;
            count++;
        }
        if(count<k) return;
        //swap nodes, same to reverse a linked list
        ListNode last = lastend.next;
        curr = lastend.next.next; 
        count = 1;
        while(count<k&&curr!=null){
            last.next = curr.next;
            curr.next = lastend.next;
            lastend.next = curr;
            count++;
            curr = last.next;
        }
        reverselist(last,k);
    }

Log in to reply
 

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