Why it works
- Every length turns bring the list back to where it was, so only k mod length turns matter. k can be far larger than the list, so the length is counted first.
- Turning by k moves the last k nodes to the front. fast goes k nodes ahead, and when it is on the tail, slow is right before those k nodes: the node to cut after.
- Three links do the turn: the tail to the old head, head to slow.next, slow.next to none. With k mod length = 0 slow ends on the tail, and the same three links give back the list unchanged.
Complexity
Time O(n): one pass to count, then fast walks the list once more; k itself does not matter after the mod. Memory O(1): a few pointers, and the nodes are relinked, not copied.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗