To reverse nodes in groups of k, we first check whether the current segment contains at least k nodes.
This gives a clean top-down approach:
solve the rest of the list first, then fix the current group.
Start at the given head and try to move forward k nodes.
k, return the current head unchanged.If exactly k nodes exist:
k nodes.k nodes:k nodes:head.nexthead.next to the result of the recursive callk nodes, return the new head of this group.The recursion ensures each segment is reversed and correctly connected to the next processed segment.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
cur = head
group = 0
while cur and group < k:
cur = cur.next
group += 1
if group == k:
cur = self.reverseKGroup(cur, k)
while group > 0:
tmp = head.next
head.next = cur
cur = head
head = tmp
group -= 1
head = cur
return headWe reverse the list one k-sized group at a time using pointers, without recursion.
Key ideas:
k nodes left, we stop (leave the rest as-is).By repeating this process, we reverse every full group of k nodes while keeping the rest of the list intact.
Create a dummy node pointing to head.
Set groupPrev = dummy (the node just before the current group).
Loop:
getKth(groupPrev, k) to find the k-th node from groupPrev.kth is null, there are fewer than k nodes left → break.Let:
groupNext = kth.next (first node after the current group).prev = groupNextcurr = groupPrev.next (first node in the current group)Reverse the current group:
curr != groupNext:curr.next in tmp.curr.next to prev.prev to curr.curr to tmp.After reversing:
groupPrev.next is now the start of the reversed group (kth node).tmp = groupPrev.next before rewiring).groupPrev.next = kth.groupPrev = tmp (now the end of the reversed group).Repeat steps 2–5 until no more full k-groups remain.
Return dummy.next as the new head of the list.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
groupPrev = dummy
while True:
kth = self.getKth(groupPrev, k)
if not kth:
break
groupNext = kth.next
prev, curr = kth.next, groupPrev.next
while curr != groupNext:
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
tmp = groupPrev.next
groupPrev.next = kth
groupPrev = tmp
return dummy.next
def getKth(self, curr, k):
while curr and k > 0:
curr = curr.next
k -= 1
return curr