← Back to DSA Animator
Reverse Nodes in k-Group LC #25 Hard Linked List · In-Place Reversal
Problem

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as is. You may not alter the values in the list's nodes, only the actual nodes themselves may be changed.

Example 1
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Constraints: 1 ≤ k ≤ n ≤ 5000  |  0 ≤ Node.val ≤ 1000
Try Examples
k-Group Bracket Visualization
Reversed (done)
Active group
Keep as-is
Pending
State Variables
Group #
k
Reversal Step
Nodes Reversed
0
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Create dummy → head. Set groupPrev = dummy.
2
Find kth node from groupPrev. If null → fewer than k remain, stop.
3
Save groupNext = kth.next. Reverse the k-group using insert-at-front: pull curr toward prev.
4
Reconnect: groupPrev.next = kth. Advance groupPrev to old group head (now tail).
5
Repeat until no full group remains. Return dummy.next.
Time
O(n)
Space
O(1)
Why It Works

The insert-at-front technique avoids tracking six pointers simultaneously. We set prev = groupNext (the node just past the k-group), then repeatedly detach curr and splice it before prev. After k iterations, what was the last node (kth) is now at the front — and groupPrev.next = kth stitches the reversed group into the list. The original group head (tmp) becomes the new groupPrev (it is now the tail).