1
# Runtime: 3864 ms (Top 51.07%) | Memory: 53.5 MB (Top 68.62%)
2
class Solution:
3
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
4
group = 2
5
tail = head # tail of previous group
6
while tail and tail.next:
7
cnt = 1 # actual size of the current group
8
cur = tail.next # first node of the current group
9
while cur.next and cnt < group:
10
cur = cur.next
11
cnt += 1
12
pre, cur = tail, tail.next
13
if cnt % 2 == 0: # if group size is even
14
while cnt and cur:
15
nxt = cur.next
16
cur.next = pre
17
pre = cur
18
cur = nxt
19
cnt -= 1
20
first = tail.next # first node of the original group
21
first.next = cur
22
tail.next = pre
23
tail = first
24
else:
25
while cnt and cur:
26
pre, cur = cur, cur.next
27
cnt -= 1
28
tail = pre
29
group += 1
30
return head

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0