Simple recursive solution in Java


  • 0
    R

    '''
    private ListNode reverseKGroup(ListNode root, int k, int curr_k) {
    if (root.next == null) {
    if (curr_k == 1) {
    return root;
    }
    return null;
    }
    if (curr_k == 1) {
    ListNode forward = reverseKGroup(root.next, k, k);
    if (forward != null) {
    root.next = forward;
    }
    return root;
    }
    ListNode res = reverseKGroup(root.next, k, curr_k -1);
    if (res == null) {
    return null;
    }
    ListNode temp = root.next.next;
    root.next.next = root;
    root.next = temp;
    return res;
    }
    '''
    '''
    public ListNode reverseKGroup(ListNode head, int k) {
    if (head == null || head.next == null || k == 1) {
    return head;
    }
    ListNode res = reverseKGroup(head, k, k);
    if (res != null) {
    return res;
    }
    return head;
    }
    '''


Log in to reply
 

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