-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.py
93 lines (73 loc) · 2.08 KB
/
LinkedList.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
"""
Basic Linked Lists implementation with Node and LinkedList classes defined
Assumptions:
------------
1. Node will be added at the head every time
"""
class Node(object):
def __init__(self, data, nextNode = None):
self.data = data
self.nextNode = None
def getData(self):
return self.data
def setData(self, data):
self.data = data
def getNext(self):
return self.nextNode
def setNext(self, nextNode):
self.nextNode = nextNode
class LList(object):
def __init__(self, head = None):
self.head = head
self.size = 0
def isEmpty(self):
return self.head == None
def getSize(self):
return self.size
def add(self, data):
newNode = Node(data)
newNode.setNext(self.head)
self.head = newNode
self.size += 1
def remove(self, data):
currNode = self.head
prevNode = None
while currNode:
if currNode.getData() == data:
if prevNode:
prevNode.setNext(currNode.getNext())
else:
self.head = currNode.getNext()
self.size -= 1
return True
else:
prevNode = currNode
currNode = currNode.getNext()
return False
def find(self, data):
currNode = self.head
while currNode:
if currNode.getData() == data:
return True
else:
currNode = currNode.getNext()
return False
def printlist(self):
currNode = self.head
while currNode != None:
print(currNode.data, end=' => ')
currNode = currNode.getNext()
if __name__ == '__main__':
myList = LList()
myList.add(5)
myList.add(8)
myList.add(12)
myList.add(34)
myList.add(43)
myList.add(82)
print (myList.printlist())
myList.remove(12)
myList.remove(82)
print (myList.printlist())
print(myList.find(34))
print (myList.printlist())