Recursive O(1) space Java solution


  • -1
    A
    public ListNode reverseKGroup(ListNode node, int k) {
        if (node == null || node.next == null) return node;
        int i = 1;
        ListNode cur = node;
        while (i < k) {
            if (cur.next == null) break;
            ListNode temp1 = cur.next;
            ListNode temp2 = cur.next.next;
            cur.next = temp2;
            temp1.next = node;
            node = temp1;
            i++;
        }
        if (i < k) {
            node = reverseKGroup(node, i);
        }else {
            cur.next = reverseKGroup(cur.next, k);
        }
        return node;
    }

Log in to reply
 

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