Short Java recursive solution


  • 0
    M
        public ListNode reverseKGroup(ListNode head, int k) {
            if (head == null || k <= 1) return head;
            ListNode cur = head;
            for (int i = 0; i < k - 1; ++i) {
                if (cur.next != null) cur = cur.next;
                else return head;
            }
            ListNode remain = cur.next;
            ListNode newH = null, node = head;
            while (node != remain) {	
                ListNode next = node.next;
                node.next = newH;
                newH = node;
                node = next;
            }
            head.next = reverseKGroup(remain, k);
            return newH;
        }
    

Log in to reply
 

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