it's easier to do recursively. Java solution


  • -1
    J

    easy to mess up in iteration. so cleaner to do recursively.

        public ListNode reverseKGroup(ListNode head, int k) {
            if (head == null || k <= 1) return head;
            ListNode end = head;
            for (int i = 1; i < k && end != null; i++) end = end.next;
            if (end != null) {
                ListNode prev = null, start = head;
                ListNode nextHead = end.next;
                ListNode saveHead = head;
                for (int i = 0; i < k; i++) {
                    ListNode next = start.next;
                    start.next = prev;
                    prev = start;
                    start = next;
                }
                ListNode more = reverseKGroup(nextHead, k);
                saveHead.next = more;
                return prev;
            } else return head;
        }
    

Log in to reply
 

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