PracticeNeetCode ↗LeetCode ↗
Given the head of a linked list, reverse the nodes k at a time and return the modified list. If the number of remaining nodes is less than k, leave that final group as-is.
k nodes available — a short trailing group is left untouched.k nodes and stitched onto the previous group's tail.head, walk k nodes ahead to check a full group exists; if not, return head unchanged (base case).k nodes in the current group with standard prev/curr pointer reversal, stopping exactly at the k-th node.Time: O(n) — Space: O(n/k) for the recursion stack
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseKGroup(head: ListNode | None, k: int) -> ListNode | None:
node = head
count = 0
while node and count < k:
node = node.next
count += 1
if count < k:
return head
prev = None
curr = head
for _ in range(k):
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
head.next = reverseKGroup(curr, k)
return prevHow the solution above works, piece by piece.
k nodes remain, return head unchanged. That's how the leftover 5 stays in place.k nodes with the prev/curr loop. Afterwards prev is the new group head and curr is the first node of the next group.head was the first node of the group and is now its last, so head.next = reverseKGroup(curr, k) connects it to the processed remainder.prev, the new head of this group.Running it on head = [1, 2, 3, 4, 5], k = 2: