Java solution O(n) time & O(1) space


  • 0
    A
    class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            int count = k;
            ListNode prev = null, curr = head, next = null;
            while(curr != null) {
                if(count == 0) {
                    break;
                }
                next = curr.next;
                curr.next = prev;
                prev = curr;
                curr = next;
                count--;
            }
            
            if(next != null) {
                head.next = reverseKGroup(next, k);
            }
            
            if(count == 0)
                return prev;
            else {
                return reverseKGroup(prev, k-count);
            }
        }
    }
    

Log in to reply
 

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