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.
head = [1,2,3,4,5], k = 2[2,1,4,3,5]head = [1,2,3,4,5], k = 3[3,2,1,4,5]dummy → head. Set groupPrev = dummy.kth node from groupPrev. If null → fewer than k remain, stop.groupNext = kth.next. Reverse the k-group using insert-at-front: pull curr toward prev.groupPrev.next = kth. Advance groupPrev to old group head (now tail).dummy.next.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).
Copying groups into arrays and rewriting values uses extra space. We can reverse each group in place.
Keep a pointer to the node before the current group. Check that k nodes exist ahead, and stop if they do not. Reverse those k nodes, connect them back, and jump to the end of the group.
Count k, reverse k, reconnect, repeat. A short tail stays untouched.
Run the animation above on your own input, or watch the 1:07 video explanation of Reverse Nodes in K-Group with a dry run and Java code.