-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathreverse.py
76 lines (58 loc) · 1.92 KB
/
reverse.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head or k == 1:
return head
# Calculate the length of the list
length, current = 0, head
while current:
length += 1
current = current.next
dummy = ListNode(next=head)
prev_node = dummy
# Reverse k-group
while length >= k:
start_node, end_node = prev_node.next, prev_node
for _ in range(k + 1):
end_node = end_node.next
next_group_start = start_node.next
for _ in range(k - 1):
tmp = start_node.next
start_node.next = tmp.next
tmp.next = prev_node.next
prev_node.next = tmp
start_node.next = end_node
prev_node = start_node
length -= k
return dummy.next
def create_linked_list(values):
dummy = ListNode()
current = dummy
for value in values:
current.next = ListNode(value)
current = current.next
return dummy.next
def linked_list_to_list(head):
values = []
current = head
while current:
values.append(current.val)
current = current.next
return values
if __name__ == '__main__':
solution = Solution()
test_cases = [
([1, 2, 3, 4, 5], 2, [2, 1, 4, 3, 5]),
([1, 2, 3, 4, 5], 3, [3, 2, 1, 4, 5]),
([1, 2, 3, 4, 5], 1, [1, 2, 3, 4, 5]),
([], 3, [])
]
for values, k, expected in test_cases:
head = create_linked_list(values)
result = solution.reverseKGroup(head, k)
result_values = linked_list_to_list(result)
assert result_values == expected, f"For {values}, k={k}, expected {expected} but got {result_values}"
print("All tests passed!")