-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.py
More file actions
123 lines (108 loc) · 2.86 KB
/
linked_list.py
File metadata and controls
123 lines (108 loc) · 2.86 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
'''
Linked-List and Sorted Linked-List Implementations
'''
from math import inf
class Cell:
def __init__(self, value, next):
self.value = value
self.next = next
class LinkedList():
def __init__(self):
self.sentinel = Cell(None, None)
self.len = 0
def insert(self, value, pos):
if pos > self.len:
print(f'ERROR: Invalid pos={pos} !')
return
cell = self.sentinel
for _ in enumerate(range(pos)):
cell = cell.next
cell.next = Cell(value, cell.next)
self.len += 1
def append(self, value):
self.insert(value, self.len)
def remove(self, pos):
if pos >= self.len:
print(f'ERROR: Invalid pos={pos} !')
return
cell = self.sentinel
for i in enumerate(range(pos)):
cell = cell.next
cell.next = cell.next.next
self.len -= 1
def __str__(self):
cell = self.sentinel
s = '['
while cell.next:
cell = cell.next
s += str(cell.value) + ', '
if len(s) > 2:
s = s[:-2] + ']'
else:
s += ']'
return s
class SortedLinkedList:
def __init__(self):
self.max = inf
self.sentinel_end = Cell(+self.max, None)
self.sentinel_begin = Cell(-self.max, self.sentinel_end)
def insert(self, value):
assert (value > -self.max) and (value < +self.max)
cell = self.sentinel_begin
while not (cell.value < value < cell.next.value):
cell = cell.next
cell.next = Cell(value, cell.next)
def remove(self, value):
prev_cell = self.sentinel_begin
cell = prev_cell.next
while cell.next:
if cell.value == value:
break
elif cell.value > value:
print(f'ERROR1: Value {value} Not Found!')
return
prev_cell, cell = cell, cell.next
else:
print(f'ERROR2: Value {value} Not Found!')
return
prev_cell.next = cell.next
def __str__(self):
cell = self.sentinel_begin
s = '['
while cell.next:
cell = cell.next
if cell.value == self.max: break
s += str(cell.value) + ', '
if len(s) > 2:
s = s[:-2] + ']'
else:
s += ']'
return s
def ll_check():
l = LinkedList()
l.insert(1, 1)
l.insert(1, 0)
l.insert(-1, 0)
l.insert(2, 2)
l.insert(3, 0)
l.append(4)
print(l)
l.remove(5)
l.remove(4)
l.remove(0)
print(l)
def sorted_ll_check():
l = SortedLinkedList()
l.insert(0)
l.insert(-1)
l.insert(2)
print(l)
l.remove(1)
l.remove(-1)
l.remove(2)
l.remove(2)
l.remove(0)
print(l)
if __name__ == '__main__':
ll_check()
sorted_ll_check()