-
Notifications
You must be signed in to change notification settings - Fork 1
/
25_reverse_nodes_in_k_group.py
59 lines (48 loc) · 1.54 KB
/
25_reverse_nodes_in_k_group.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:param head: ListNode
:param k: int
:return: ListNode
"""
nodes = []
current = head
while current:
nodes.append(current)
current = current.next
if len(nodes) == 0:
return None
elif len(nodes) < k:
return head
reverse_nodes_head = ListNode(0)
reverse_nodes_tail = reverse_nodes_head
i = 1
while i * k <= len(nodes):
index = k * i - 1
while index >= k * (i - 1):
reverse_nodes_tail.next = nodes[index]
reverse_nodes_tail = reverse_nodes_tail.next
index -= 1
i += 1
if len(nodes) % k != 0:
reverse_nodes_tail.next = nodes[k * (i - 1)]
else:
reverse_nodes_tail.next = None
return reverse_nodes_head.next
assert Solution().reverseKGroup(None, 1) is None
assert Solution().reverseKGroup(ListNode(1), 2).val == 1
head_node = ListNode(1)
head_node.next = ListNode(2)
head_node.next.next = ListNode(3)
head_node.next.next.next = ListNode(4)
head_node.next.next.next.next = ListNode(5)
head_node = Solution().reverseKGroup(head_node, 2)
assert head_node.val == 2
assert head_node.next.val == 1
assert head_node.next.next.val == 4
assert head_node.next.next.next.val == 3
assert head_node.next.next.next.next.val == 5