Skip to content

Commit a4a8d78

Browse files
Merge pull request #90 from realpython/linked-lists-python
Create linked-lists-python.py
2 parents 790e912 + 7fafe2e commit a4a8d78

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
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+
new_node.next = node.next
54+
node.next = new_node
55+
return
56+
57+
raise Exception("Node with data '%s' not found" % target_node_data)
58+
59+
def add_before(self, target_node_data, new_node):
60+
if not self.head:
61+
raise Exception("List is empty")
62+
63+
if self.head.data == target_node_data:
64+
return self.add_first(new_node)
65+
66+
prev_node = self.head
67+
for node in self:
68+
if node.data == target_node_data:
69+
prev_node.next = new_node
70+
new_node.next = node
71+
return
72+
prev_node = node
73+
74+
raise Exception("Node with data '%s' not found" % target_node_data)
75+
76+
def remove_node(self, target_node_data):
77+
if not self.head:
78+
raise Exception("List is empty")
79+
80+
if self.head.data == target_node_data:
81+
self.head = self.head.next
82+
return
83+
84+
previous_node = self.head
85+
for node in self:
86+
if node.data == target_node_data:
87+
previous_node.next = node.next
88+
return
89+
previous_node = node
90+
91+
raise Exception("Node with data '%s' not found" % target_node_data)

0 commit comments

Comments
 (0)