Reverse Nodes in k-Group

Problem Description

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list's nodes, only nodes themselves may be changed.

 

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Example 2:

Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]

 

Constraints:

 

Follow-up: Can you solve the problem in O(1) extra memory space?

Solution (JavaScript)

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
const reverseKGroup = function(head, k) {
    const swapPairs = function(head) {
        if(!head || !head.next) 
            return head;
        let r = head.next;
        head.next = r.next
        r.next = head;
        head.next = swapPairs(head.next);
        return r;
    };
    
    if(k === 1) return head;
    if(k === 2) return swapPairs(head);
    
    function getLen(head, l) {
        if(!head) return l;
        return getLen(head.next, l+1);
    }
    
    function reverseGroup(h, k, f) {
        if(f === 0) return h;
        
        let l = h;
        let m = l.next;
        let r = m.next;
        for(let i = 0; i < k-2; i++) {
            m.next = l;
            l = m;
            m = r;
            r = r.next;
        }
        m.next = l;
        h.next = reverseGroup(r, k, f-1);
        return m;
    }
    
    return reverseGroup(head, k, Math.floor(getLen(head, 0)/k));
};