1
# Definition for singly-linked list.
2
class ListNode:
3
def __init__(self, val=0, next=None):
4
self.val = val
5
self.next = next
6

7

8
class Solution:
9
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
10

11
# Intialize the result and the current node to the head
12
res = node = head
13

14
# Initialize the index of the current node to 0
15
i = 0
16

17
# Initialize the head and tail of the reversed nodes group to None
18
reversedHead, reversedTail = None, None
19

20
# Initialize the tail of the previous group to None
21
previousTail = None
22

23
# Iterate through all nodes
24
while node:
25

26
# When we reach the first node in a group
27
if i % k == 0:
28

29
# If there is a previous group, connect its tail to the current node
30
# This is the case when we have less than k nodes left
31
if previousTail:
32
previousTail.next = node
33

34
# Initialize the head and tail of the reversed nodes group
35
reversedHead = reversedTail = ListNode(node.val)
36

37
# Continue to reverse subsequent nodes
38
else:
39
reversedHead = ListNode(node.val, reversedHead)
40

41
# If we are able to reach the last node in a reversed nodes group
42
if i % k == k - 1:
43

44
# If there is a previous group, connect its tail to the current node
45
# This is the case when we have k nodes and thus, we should reverse this group
46
if previousTail:
47
previousTail.next = reversedHead
48

49
# Set the tail of the previous group to the tail of the reversed nodes group
50
previousTail = reversedTail
51

52
# Set the head of the first reversed nodes group as the result
53
if i == k - 1:
54
res = reversedHead
55

56
# Continue to the next node
57
i, node = i + 1, node.next
58

59
return res

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0