Why it works
- end counts k nodes before a single link changes, so a short tail is found while it is still intact and is left as it is.
- Each group is reversed by the card's loop, run exactly k times; after it, prev is the group's new first node and cur the first node after the group.
- before.next = prev and first.next = cur sew the group back in, and the old first node, now its last, becomes before for the next group.
Complexity
Time O(n): every node is counted once and turned around at most once. Memory O(1): a few pointers and one dummy node.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗