JSFiddle - React, Tailwind, and code Playground

by krishna chaitanya nalluri

JavaScript

function reverseKGroup(head, k) {
    const stack = [], preHead = new ListNode();
    preHead.next = head;
    let lastTail = preHead;
    while (head) {
        for (let i = 0; i < k && head; i++) {
            stack.push(head);
            head = head.next;
        }
        if (stack.length === k) {
            while (stack.length > 0) {
                lastTail.next = stack.pop();
                lastTail = lastTail.next;
            }
            lastTail.next = head;
        }
    }

    return preHead.next;
}