Why it works
- before stops on the node in front of the part, and the dummy guarantees there is one: with left = 1 before stays on the dummy, and dummy.next becomes the new head.
- Inside the part it is the card's reverse loop, run exactly right − left + 1 times; then cur stands on the first node after the part.
- Two links sew the part back: before → prev, its new first node, and first, now its last node, → cur. Every other link is untouched.
Complexity
Time O(n): before walks to the part, the loop walks through it, each node once at most. Memory O(1): a few pointers and one dummy node.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗