class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
# Helper function to reverse a part of the linked list.
def reverseLinkedList(start, end):
prev, curr = None, start
while curr != end:
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp
return prev
# Dummy node to handle edge cases easily.
dummy = ListNode(0)
dummy.next = head
prev_group_end = dummy
while True:
kth_node = prev_group_end
# Find the kth node from the current position.
for _ in range(k):
kth_node = kth_node.next
if not kth_node:
return dummy.next # Return the new head of the list.
# Mark the end of the next group.
next_group_start = kth_node.next
# Reverse the current group.
new_group_start = reverseLinkedList(prev_group_end.next, next_group_start)
# Connect the reversed group with the rest of the list.
temp = prev_group_end.next
prev_group_end.next = new_group_start
prev_group_end = temp
# Set the next node for traversal.
prev_group_end.next = next_group_start