Pattern visualizer
Reverse Linked List II
Reversing a middle segment is awkward with the usual three-pointer reversal because four boundary pointers have to be stitched back together at the end. Head insertion avoids the stitching entirely. Fix one anchor, pre, on the node just before the window and keep start on the window's first node. Each step plucks the node after start and re-inserts it directly after pre. The plucked node lands in front of everything reversed so far, and start is pushed one slot to the right without being moved explicitly. After n - m such moves the window is reversed and both boundaries were maintained the whole time. The dummy node means the anchor exists even when the window begins at the head. Animated on: list = [1, 2, 3, 4, 5], m = 2, n = 4. Reverse the nodes from position m to n (1-indexed) in one pass. Answer: [1, 4, 3, 2, 5]..
Head insertion behind a fixed anchor, one pass
Reverse only positions 2..4 (1-indexed), the tinted window, in one pass. A dummy node sits before the head so the node BEFORE the window always exists — even when m = 1 and the window starts at the head.
1FUNCTION reverseBetween(head, m, n)2 dummy.next <- head3 pre <- dummy4 FOR i <- 1 TO m - 15 pre <- pre.next6 start <- pre.next7 FOR i <- 1 TO n - m8 then <- start.next9 start.next <- then.next10 then.next <- pre.next11 pre.next <- then12 RETURN dummy.next
← / → step · space play · Home restart