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
92 lines (69 loc) · 2.08 KB
/
Copy pathsingly_linked_list.py
File metadata and controls
92 lines (69 loc) · 2.08 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Singly Linked List
------------------
A linked list is a data structure consisting of a group of nodes which
together represent a sequence. Under the simplest form, each node is
composed of data and a reference (in other words, a link) to the next
node in the sequence; more complex variants add additional links. This
structure allows for efficient insertion or removal of elements from any
position in the sequence.
Pseudo Code: https://en.wikipedia.org/wiki/Linked_list
"""
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def set_next(self, next):
self.next = next
def get_next(self):
return self.next
class SinglyLinkedList:
def __init__(self):
self.head = None
self.size = 0
def add(self, value):
"""
Add element to list
Time Complexity: O(N)
"""
node = Node(value)
node.set_next(self.head)
self.head = node
self.size += 1
def _search_node(self, value, remove=False):
current = self.head
previous = None
while current:
if current.data == value:
break
else:
previous = current
current = current.next
if remove and current:
if previous is None: # Head node
self.head = current.next
else: # None head node
previous.set_next(current.next)
self.size -= 1
return current is not None
def remove(self, value):
"""
Remove element from list
Time Complexity: O(N)
"""
return self._search_node(value, True)
def search(self, value):
"""
Search for value in list
Time Complexity: O(N)
"""
return self._search_node(value)
def size(self):
"""
Return size of list
"""
return self.size