-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunrolled_linked_list.py
135 lines (105 loc) · 3.63 KB
/
unrolled_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
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
124
125
126
127
128
129
130
131
132
133
134
135
class Elem:
def __init__(self,size = 6) -> None:
self.node = [None for i in range(size)]
self.nbElem = 0
self.next = None
class Unrolled_list:
def __init__(self,size = 6) -> None:
self.tab = []
self.size = size
self.head = None
self.tail = None
self.nbNode = 0
def get(self,idx):
count = 0
for tab in self.tab:
for val in tab.node:
if val:
count += 1
if count - 1 == idx:
return val
def insert(self,idx,data):
if not self.tab:
current = Elem()
self.head = current
self.tab.append(current)
self.nbNode += 1
if idx < self.size and self.head.node[idx] is None:
self.head.node[idx] = data
self.head.nbElem += 1
return
node_idx = idx // self.size
if node_idx < len(self.tab):
current = self.tab[node_idx]
if current.node[idx % self.size]:
if current.nbElem == self.size:
new_n = Elem()
self.tab.insert(node_idx + 1,new_n)
for i in range(self.size // 2):
new_n.node[i] = current.node[self.size // 2 + i]
current.node[self.size // 2 + i] = None
if idx > self.size:
new_n.node[idx] = data
new_n.nbElem += 1
return
else:
elem = current.node[idx]
current.node[idx] = None
current.node[idx + 1:] = current.node[idx:-1]
current.node[idx] = data
current.node[idx + 1] = elem
current.node[idx] = data
current.nbElem += 1
return
else:
elem = current.node[idx % self.size]
current.node[idx % self.size] = None
current.node[idx % self.size + 1:] = current.node[idx % self.size:-1]
current.node[idx % self.size] = data
current.node[idx % self.size + 1] = elem
return
i = 0
while node_idx > 0:
i += 1
node_idx -= 1
try:
current = self.tab[i]
except IndexError:
current = Elem()
self.tab.append(current)
self.nbNode += 1
current.node[idx % self.size] = data
current.nbElem += 1
return
def display(self):
for idx, elem in enumerate(self.tab):
print(f"Node {idx}: {elem.node}")
def delete(self,idx):
count = 0
c_tab = 0
for tab in self.tab:
c_tab += 1
c_val = 0
for val in tab.node:
c_val += 1
if val:
count += 1
if count - 1 == idx:
curr = self.tab[c_tab - 1]
curr.node[c_val - 1] = None
return
def main():
size = 6
tab = Unrolled_list(size)
for i in range(1,10):
tab.insert(i-1,i)
tab.display()
print(tab.get(4))
tab.insert(1,10)
tab.display()
tab.insert(8,11)
tab.display()
tab.delete(1)
tab.delete(2)
tab.display()
main()