forked from learning-zone/python-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.py
100 lines (63 loc) · 2.05 KB
/
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
88
89
90
91
92
93
94
""" Implement a singly linked list. """
class Node(object):
""" Creates a node. """
def __init__(self, data=None, nxt=None):
self.data = data
self.next = nxt
class LinkedList(object):
""" Creates a linked list. """
def __init__(self, head=None):
self.head = head
self.tail = tail
def insert(self, data, position):
""" Takes data as an input and a position and adds it to the linked list as a node before that position. """
new_node = Node(data)
if position == 0:
new_node.next = self.head
self.head = new_node
if position == self.size():
self.tail.next = new_node
self.tail = new_node
prev = None
curr = self.head
index = 0
while curr.next:
if position == index:
prev.next = new_node
new_node.next = curr
return
index +=1
prev = prev.next
curr = curr.next
def size(self):
""" Returns the length of the linked list. """
size = 0
if head is None and tail is None:
return size
curr = self.head
while curr:
size += 1
curr = curr.next
return size
def search(self, data):
""" Takes data as an input and returns the node holding the data. """
curr = self.head
while curr:
if curr.data == data:
return curr
curr = curr.next
raise ValueError('Data not in linked list.')
def delete(self, data):
""" Takes data as an input and deletes the node with that data. """
prev = None
curr = self.head
while curr:
if curr.data == data:
if curr == self.head:
self.head = curr.next
else:
prev.next = curr.next
prev = curr
curr = curr.next
if curr is None:
raise ValueError('Data not in linked list.')