Reverse the nodes of a linked list k at a time. If the number of remaining nodes is less than k, leave them as is. Only node links may change, not values.
Keep a pointer to the node before the current group. Check that k nodes remain, reverse them with the usual prev/curr loop, then splice the reversed group back between its neighbours.
1function reverseKGroup(head: ListNode | null, k: number): ListNode | null {2const dummy = new ListNode(0, head);3let before = dummy;4while (true) {5let kth: ListNode | null = before;6for (let i = 0; i < k && kth; i++) kth = kth.next;7if (!kth) break;8const after = kth.next, first = before.next!;9let prev = after, curr: ListNode | null = first;10while (curr !== after) { const nx: ListNode | null = curr!.next; curr!.next = prev; prev = curr; curr = nx; }11before.next = kth;12before = first;13}14return dummy.next;15}
A dummy head makes the first group like any other.
Space: play/pause · ←/→: step