1
# Definition for singly-linked list.3
def __init__(self, val=0, next=None):9
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:11
# Intialize the result and the current node to the head14
# Initialize the index of the current node to 017
# Initialize the head and tail of the reversed nodes group to None18
reversedHead, reversedTail = None, None20
# Initialize the tail of the previous group to None23
# Iterate through all nodes26
# When we reach the first node in a group29
# If there is a previous group, connect its tail to the current node30
# This is the case when we have less than k nodes left32
previousTail.next = node34
# Initialize the head and tail of the reversed nodes group35
reversedHead = reversedTail = ListNode(node.val)37
# Continue to reverse subsequent nodes39
reversedHead = ListNode(node.val, reversedHead)41
# If we are able to reach the last node in a reversed nodes group44
# If there is a previous group, connect its tail to the current node45
# This is the case when we have k nodes and thus, we should reverse this group47
previousTail.next = reversedHead49
# Set the tail of the previous group to the tail of the reversed nodes group50
previousTail = reversedTail52
# Set the head of the first reversed nodes group as the result56
# Continue to the next node57
i, node = i + 1, node.next