Skip to content

Commit f8fe944

Browse files
committed
create unordered list in python
added unordered list in python
1 parent 5531625 commit f8fe944

File tree

1 file changed

+115
-0
lines changed

1 file changed

+115
-0
lines changed

src/python/unordered_linked_list.py

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
2+
class Node:
3+
4+
def __init__(self,value,rptr=None) -> None:
5+
self.value = value
6+
self.rptr = rptr
7+
8+
@property
9+
def get_value(self):
10+
return self.value
11+
12+
@property
13+
def next(self):
14+
return self.rptr
15+
16+
@next.setter
17+
def next(self,ptr):
18+
self.rptr = ptr
19+
20+
21+
class Unordered_Linked_List:
22+
def __init__(self) -> None:
23+
self.first_node = None
24+
25+
def insert(self,value): # inserts a new node with the given value
26+
if self.first_node is None:
27+
self.first_node = Node(value)
28+
else:
29+
tmp = Node(value)
30+
tmp.next = self.first_node
31+
self.first_node = tmp
32+
33+
def find(self,value): # returns true if the specified value is in your list
34+
ptr = self.first_node
35+
while ptr is not None:
36+
if ptr.value == value:
37+
print(f'{value} is in your list')
38+
return True
39+
else:
40+
ptr = ptr.next
41+
42+
print(f'{value} is not in your list')
43+
return False
44+
45+
def size(self): # returns size of the list
46+
ptr = self.first_node
47+
i = 0
48+
while ptr is not None:
49+
ptr = ptr.next
50+
i+=1
51+
print(f'Your list is of size {i}')
52+
return i
53+
54+
def remove(self,value): # removes all instances of a given value
55+
ptr = self.first_node
56+
prev = None
57+
while ptr is not None:
58+
if ptr.value == value:
59+
if ptr == self.first_node:
60+
tmp = ptr.next
61+
self.first_node = tmp
62+
else:
63+
prev.next = ptr.next
64+
65+
prev = ptr
66+
ptr = ptr.next
67+
68+
def show(self):
69+
ptr = self.first_node
70+
val = []
71+
while ptr is not None:
72+
val.append(ptr.get_value)
73+
ptr = ptr.next
74+
75+
print(val)
76+
77+
def main():
78+
list = Unordered_Linked_List()
79+
80+
list.insert(1)
81+
list.insert(3)
82+
list.insert(5)
83+
list.insert(2)
84+
85+
list.size()
86+
list.show()
87+
88+
list.find(3)
89+
list.find(9)
90+
91+
list.remove(1)
92+
list.remove(3)
93+
list.remove(5)
94+
list.remove(2)
95+
96+
list.show()
97+
98+
list.insert(1)
99+
list.insert(3)
100+
list.insert(5)
101+
list.insert(3)
102+
103+
list.show()
104+
105+
list.remove(3)
106+
107+
list.show()
108+
109+
110+
111+
112+
if __name__ == "__main__":
113+
main()
114+
115+

0 commit comments

Comments
 (0)