# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    def reverseKGroup(self , head: ListNode, k: int) -> ListNode:
        # write code here
        pre = None
        cur = head

        # 节点从1编号,找到第k+1个节点
        tail = head
        for i in range(k):
            if not tail:
                return head
            tail = tail.next
        # 对前k个节点翻转
        while cur != tail:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        # 对k+1及以后的节点翻转
        head.next = self.reverseKGroup(cur, k)
        return pre