forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
singly_linked_list.py
87 lines (61 loc) · 1.87 KB
/
singly_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
"""
Linked List:
_________ _________ _________ _________
head --> | 2 | --|--> | 1 | --|--> | 5 | --|--> | 3 | --|--> None
--------- --------- --------- ---------
"""
class Node:
def __init__(self, value, next_node=None):
self.__value = value
self.next_node = next_node
@property
def value(self):
return self.__value
class LinkedList:
def __init__(self):
self.__main_node = None
def append(self, value):
if self.__main_node is None:
self.__main_node = Node(value)
return
curr_node = self.__main_node
while curr_node.next_node is not None:
curr_node = curr_node.next_node
curr_node.next_node = Node(value)
def remove(self, value):
if self.__main_node is None:
return
left_node = None
curr_node = self.__main_node
if curr_node.value == value:
self.__main_node = curr_node.next_node
while True:
left_node = curr_node
curr_node = curr_node.next_node
if curr_node is None:
break
if curr_node.value == value:
left_node.next_node = curr_node.next_node
def show(self):
values = []
curr_node = self.__main_node
while curr_node is not None:
values.append(curr_node.value)
curr_node = curr_node.next_node
print("LinkedList: {}".format(values))
def main():
linked_list = LinkedList()
linked_list.append(5)
linked_list.append(9)
linked_list.append(2)
linked_list.show()
linked_list.remove(9)
linked_list.show()
linked_list.remove(5)
linked_list.remove(9)
linked_list.remove(2)
linked_list.show()
linked_list.append(8)
linked_list.show()
if __name__ == "__main__":
main()