forked from nryoung/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingly_linked_list.py
More file actions
74 lines (57 loc) · 1.28 KB
/
Copy pathsingly_linked_list.py
File metadata and controls
74 lines (57 loc) · 1.28 KB
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
"""
Singly Linked List data structure implemented:
--------------------------------
add : add element to list
remove : remove element from list
search : search for value in list
size : return size of list
Time Complexity: O(N)
"""
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def setData(self, data):
self.data = data
def getData(self):
return self.data
def setNext(self, next):
self.next = next
def getNext(self):
return self.next
class SinglyLinkedList:
def __init__(self):
self.head = None
self.size = 0
def add(self, value):
node = Node(value)
node.setNext(self.head)
self.head = node
self.size += 1
def remove(self, value):
current = self.head
previous = None
found = False
while not found:
if current.data == value:
found = True
self.size-=1
else:
previous = current
current = current.next
if previous == None: # Head node
self.head = current.next
else: # None head node
previous.setNext(current.next)
return found
def search(self, value):
current = self.head
found = False
while current and not found:
if current.getData() == value:
found = True
else:
current = current.next
return found
def size(self):
return self.size