-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathreverse_linked_list.py
60 lines (41 loc) · 1.06 KB
/
reverse_linked_list.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
import unittest
class Node:
def __init__(self, data):
self.data = data
self.next = None
def k_reverse(reversed, remain, k):
if not remain:
return reversed
count = k
start = remain
while count > 0 and remain.next:
remain = remain.next
count -= 1
end = remain
next = remain.next
remain.next = reversed
reversed = remain
return reverse(reversed, next)
def reverse(reversed, remain):
if not remain:
return reversed
next = remain.next
remain.next = reversed
reversed = remain
return reverse(reversed, next)
def print_linked_list(link: Node):
while link:
print(f"{link.data} -> ", end="")
link = link.next
print(f"Null")
class TestCase(unittest.TestCase):
def test_reverse(self):
head = None
for i in range(10, 0, -1):
node = Node(i)
node.next = head
head = node
result = reverse(None, head)
print_linked_list(result)
if __name__ == "__main__":
unittest.main()