Easy to understand java recursive solution with explanation


  • 0
    J
        public ListNode reverseKGroup(ListNode head, int k) {
            if (head == null) return null;
            int count = 1;
            ListNode curr = head;
            while (curr != null) {
                if (count == k) {
                    ListNode next = curr.next;
                    // Reverse from head ... curr and get the first element of reversed list
                    curr.next = null;
                    ListNode revHead = reverseList(head, null);
                    // Think of example [1,2,3,4]   when k = 2
                    // The head should always connect to next group's return value (first element)
                    head.next = reverseKGroup(next,k);
                    // The first element in current reversed group is the return value from reverse function
                    return revHead;
                }
                count++;
                curr = curr.next;
            }
            return head;
        }
        
        // Recursive reverse helper
        public ListNode reverseList(ListNode head, ListNode newHead) {
            if (head == null) return newHead;
            ListNode next = head.next;
            head.next = newHead;
            return reverseList(next,head);
        }
    }

Log in to reply
 

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