-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingly_linked_list_2.py
116 lines (101 loc) · 2.94 KB
/
singly_linked_list_2.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
class Node:
def __init__(self, data: any) -> None:
self.data = data
self.next = None
def __str__(self) -> str:
return str(self.data)
class SinglyLinkedList:
def __init__(self) -> None:
self.head = None
self.tail = None
def __len__(self) -> int:
size = 0
run = self.head
while run:
size += 1
run = run.next
return size
def __iter__(self) -> None:
run = self.head
while run:
yield run
run = run.next
def __str__(self) -> str:
if self.is_empty():
return "List is Empty"
else:
return '->'.join([str(node) for node in self])
def node(self, index: int) -> Node:
for i, node in enumerate(self):
if i == index:
return node
def is_empty(self) -> bool:
return not bool(self.head)
def append(self, data: any) -> None:
node = Node(data)
if self.is_empty():
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def add_head(self, data: any) -> None:
node = Node(data)
if self.is_empty():
self.head = node
self.tail = node
else:
node.next = self.head
self.head = node
def insert(self, index: int, data: any) -> None:
node = Node(data)
size = len(self)
if (size == 0 and index == 0) or index == size:
self.append(data)
elif index == 0:
node.next = self.head
self.head = node
elif index > 0 and index < size:
temp = self.node(index-1)
node.next = temp.next
temp.next = node
def remove_index(self, index: int) -> None:
size = len(self)
if self.is_empty():
return
if index == 0:
self.head = self.head.next
elif index > 0 and index < size:
temp = self.node(index-1)
temp.next = temp.next.next
if index == size-1:
self.tail = temp
def remove_data(self, data: any) -> None:
if self.is_empty():
return
if self.head.data == data:
self.head = self.head.next
return
for node in self:
if node.next and node.next.data == data:
temp = node.next
node.next = node.next.next
if self.tail.data == temp.data:
self.tail = node
break
def main():
pass
# sll = SinglyLinkedList()
# sll.append(0)
# sll.append(1)
# sll.append(2)
# sll.add_head(3)
# sll.insert(1,5)
# sll.remove_index(2)
# sll.remove_data(2)
# print(sll)
# print(sll.node(1))
# print(len(sll))
# print(sll.is_empty())
if __name__ == '__main__':
main()