-
Notifications
You must be signed in to change notification settings - Fork 0
/
singly_linked_list.py
74 lines (58 loc) · 1.66 KB
/
singly_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
class Node:
"""
class implementation for a singly linked list node
Args:
data: node data
nextNode: the next node
"""
def __init__(self, data=None, nextNode=None):
self.data = data
self.nextNode = nextNode
def getData(self):
return self.data
def setData(self, data):
self.data = data
def getNextNode(self):
return self.nextNode
def setNextNode(self, nextNode):
self.nextNode = nextNode
def __repr__(self):
return repr(self.data)
class LinkedList:
"""
class implementation for a singly linked list node
Args:
data: node data
nextNode: the next node
"""
def __init__(self, head=None):
self.head = head
self.size = 0
def __repr__(self):
nodes = []
curr = self.head
while curr:
nodes.append(repr(curr))
curr = curr.nextNode
return '[' + ','.join(nodes) + ']'
def getSize(self):
return self.size
def prepend(self, data):
self.head = Node(data, self.head)
def append(self, data):
newNode = Node(data, self.head)
self.head = newNode
self.size += 1
return True
def remove(self, key):
curr = self.head
prev = None
if curr:
while curr and curr.data != key:
prev = curr
curr = curr.nextNode
if prev is None:
self.head = curr.nextNode
elif curr:
prev.nextNode = curr.nextNode
curr.nextNode = None