Skip to content

Commit cbe8b58

Browse files
committed
Create linked_list.py
1 parent 63b2557 commit cbe8b58

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

linked_list.py

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
""" Implement a singly linked list. """
2+
3+
class Node(object):
4+
""" Creates a node. """
5+
6+
def __init__(self, data=None, nxt=None):
7+
self.data = data
8+
self.next = nxt
9+
10+
11+
12+
class LinkedList(object):
13+
""" Creates a linked list. """
14+
15+
def __init__(self, head=None):
16+
self.head = head
17+
self.tail = tail
18+
19+
def insert(self, data, position):
20+
""" Takes data as an input and a position and adds it to the linked list as a node before that position. """
21+
22+
new_node = Node(data)
23+
24+
if position == 0:
25+
new_node.next = self.head
26+
self.head = new_node
27+
28+
if position == self.size():
29+
self.tail.next = new_node
30+
self.tail = new_node
31+
32+
33+
prev = None
34+
curr = self.head
35+
index = 0
36+
37+
while curr.next:
38+
if position == index:
39+
prev.next = new_node
40+
new_node.next = curr
41+
return
42+
index +=1
43+
prev = prev.next
44+
curr = curr.next
45+
46+
47+
def size(self):
48+
""" Returns the length of the linked list. """
49+
50+
size = 0
51+
52+
if head is None and tail is None:
53+
return size
54+
55+
curr = self.head
56+
57+
while curr:
58+
size += 1
59+
curr = curr.next
60+
61+
return size
62+
63+
64+
def search(self, data):
65+
""" Takes data as an input and returns the node holding the data. """
66+
67+
curr = self.head
68+
69+
while curr:
70+
if curr.data == data:
71+
return curr
72+
curr = curr.next
73+
74+
raise ValueError('Data not in linked list.')
75+
76+
77+
def delete(self, data):
78+
""" Takes data as an input and deletes the node with that data. """
79+
80+
prev = None
81+
curr = self.head
82+
83+
while curr:
84+
if curr.data == data:
85+
if curr == self.head:
86+
self.head = curr.next
87+
else:
88+
prev.next = curr.next
89+
90+
prev = curr
91+
curr = curr.next
92+
93+
if curr is None:
94+
raise ValueError('Data not in linked list.')
95+
96+
97+
98+
99+
100+

0 commit comments

Comments
 (0)