function reverseKGroup(head: ListNode | null, k: number): ListNode | null {
const reverseLinkedList = (start: ListNode | null, end: ListNode | null): ListNode | null => {
let prev: ListNode | null = null, curr = start;
while (curr !== end) {
const nextTemp: ListNode | null = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
};
const dummy = new ListNode(0);
dummy.next = head;
let prevGroupEnd: ListNode = dummy;
while (true) {
let kthNode: ListNode | null = prevGroupEnd;
for (let i = 0; i < k; i++) {
if (kthNode === null) break;
kthNode = kthNode.next;
}
if (kthNode === null) return dummy.next;
const nextGroupStart: ListNode | null = kthNode.next;
const newGroupStart = reverseLinkedList(prevGroupEnd.next, nextGroupStart);
const temp: ListNode | null = prevGroupEnd.next;
prevGroupEnd.next = newGroupStart;
prevGroupEnd = temp;
prevGroupEnd.next = nextGroupStart;
}
}