-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list_reverse.py
More file actions
87 lines (70 loc) · 2.5 KB
/
Copy pathlinked_list_reverse.py
File metadata and controls
87 lines (70 loc) · 2.5 KB
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
77
78
79
80
81
82
83
84
85
86
87
"""
Домашнее задание для лекции "Задачки на собеседованиях для продвинутых,
с тонкостями языка"
Описание
1. Перестроить заданный связанный список (LinkedList) в обратном порядке.
Для этого использовать метод `LinkedList.reverse()`, представленный
в данном файле.
2. Определить сложность алгоритма.
3. Определить потребление памяти в big-O notation.
Примечание
Проверить работоспособность решения можно при помощи тестов,
которые можно запустить следующей командой:
python3 -m unittest linked_list_reverse.py
"""
import unittest
from typing import Iterable
class LinkedListNode:
def __init__(self, data):
self.data = data
self.next = None # type: LinkedListNode
class LinkedList:
def __init__(self, values: Iterable):
previous = None
self.head = None
for value in values:
current = LinkedListNode(value)
if previous:
previous.next = current
self.head = self.head or current
previous = current
def __iter__(self):
current = self.head
while current:
yield current.data
current = current.next
def reverse(self) -> None:
# raise NotImplementedError
class LinkedListTestCase(unittest.TestCase):
def test_reverse(self):
cases = dict(
empty=dict(
items=[],
expected_items=[],
),
single=dict(
items=[1],
expected_items=[1],
),
double=dict(
items=[1, 2],
expected_items=[2, 1],
),
triple=dict(
items=[1, 2, 3],
expected_items=[3, 2, 1],
),
)
for case, data in cases.items():
with self.subTest(case=case):
linked_list = LinkedList(data['items'])
linked_list.reverse()
self.assertListEqual(
data['expected_items'],
list(linked_list),
)
def main():
link_list = LinkedList([1, 2, 3, 4])
print(link_list)
if __name__ == '__main__':
main()