25. Reverse Nodes in k-Group

202407291510
tags: #linked-list

var reverseKGroup = function(head, k) {
	let n = 0;
	for (let cur = head; cur != null; cur = cur.next) {
		n += 1;
	}
	const dummy = new ListNode(0);
	dummy.next = head;
	for (let prev = dummy, cur = head; n >= k; n -= k) {
		for (let i = 1; i < k; i++) {
			const next = cur.next.next;
			cur.next.next = prev.next;
			prev.next = cur.next;
			cur.next = next;
		}
		prev = cur;
		cur = cur.next;
	}
	return dummy.next;
};

Reference

https://leetcode.com/problems/reverse-nodes-in-k-group