Beautiful JavaScript Code


  • 1
    D
    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;
    }
    

Log in to reply
 

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