1# Runtime: 3864 ms (Top 51.07%) | Memory: 53.5 MB (Top 68.62%)2class Solution:3def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:4group = 25tail = head # tail of previous group6while tail and tail.next:7cnt = 1 # actual size of the current group8cur = tail.next # first node of the current group9while cur.next and cnt < group:10cur = cur.next11cnt += 112pre, cur = tail, tail.next13if cnt % 2 == 0: # if group size is even14while cnt and cur:15nxt = cur.next16cur.next = pre17pre = cur18cur = nxt19cnt -= 120first = tail.next # first node of the original group21first.next = cur22tail.next = pre23tail = first24else:25while cnt and cur:26pre, cur = cur, cur.next27cnt -= 128tail = pre29group += 130return head