Skip to content

Commit 2a2e8c0

Browse files
Create linked-lists-python.py
1 parent 790e912 commit 2a2e8c0

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
class Node:
2+
def __init__(self, data):
3+
self.data = data
4+
self.next = None
5+
6+
def __repr__(self):
7+
return self.data
8+
9+
10+
class LinkedList:
11+
def __init__(self, nodes=None):
12+
self.head = None
13+
if nodes is not None:
14+
node = Node(data=nodes.pop(0))
15+
self.head = node
16+
for elem in nodes:
17+
node.next = Node(data=elem)
18+
node = node.next
19+
20+
def __repr__(self):
21+
node = self.head
22+
nodes = []
23+
while node is not None:
24+
nodes.append(node.data)
25+
node = node.next
26+
nodes.append("None")
27+
return " -> ".join(nodes)
28+
29+
def __iter__(self):
30+
node = self.head
31+
while node is not None:
32+
yield node
33+
node = node.next
34+
35+
def add_first(self, node):
36+
node.next = self.head
37+
self.head = node
38+
39+
def add_last(self, node):
40+
if not self.head:
41+
self.head = node
42+
return
43+
for current_node in self:
44+
pass
45+
current_node.next = node
46+
47+
def add_after(self, target_node_data, new_node):
48+
if not self.head:
49+
raise Exception("List is empty")
50+
51+
for node in self:
52+
if node.data != target_node_data:
53+
continue
54+
new_node.next = node.next
55+
node.next = new_node
56+
return
57+
58+
raise Exception("Node with data '%s' not found" % target_node_data)
59+
60+
def add_before(self, target_node_data, new_node):
61+
if not self.head:
62+
raise Exception("List is empty")
63+
64+
if self.head.data == target_node_data:
65+
return self.add_first(new_node)
66+
67+
prev_node = self.head
68+
for node in self:
69+
if node.data == target_node_data:
70+
prev_node.next = new_node
71+
new_node.next = node
72+
return
73+
prev_node = node
74+
75+
raise Exception("Node with data '%s' not found" % target_node_data)
76+
77+
def remove_node(self, target_node_data):
78+
if not self.head:
79+
raise Exception("List is empty")
80+
81+
if self.head.data == target_node_data:
82+
self.head = self.head.next
83+
return
84+
85+
previous_node = self.head
86+
for node in self:
87+
if node.data == target_node_data:
88+
previous_node.next = node.next
89+
return
90+
previous_node = node
91+
92+
raise Exception("Node with data '%s' not found" % target_node_data)

0 commit comments

Comments
 (0)