-
Notifications
You must be signed in to change notification settings - Fork 601
/
Copy pathP31_SinglyLinkedList.py
95 lines (74 loc) · 2.2 KB
/
P31_SinglyLinkedList.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
95
#This program illustrates an example of singly linked list
#Linked lists do NOT support random access hence only sequential search can be carried out
class Node(object):
def __init__(self, data, Next = None):
self.data = data
self.next = Next
def getData(self):
return self.data
def setData(self, data):
self.data = data
def getNext(self):
return self.next
def setNext(self, newNext):
self.next = newNext
class LinkedList(object):
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self, element):
temp = Node(element)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
def getAllData(self):
current = self.head
elements = []
while current:
elements.append(current.getData())
current = current.getNext()
return elements
if __name__ == '__main__':
myList = LinkedList()
print(myList.head) # None
myList.add(12)
myList.add(2)
myList.add(22)
myList.add(32)
myList.add(42)
print(myList.size()) # 5
print(myList.search(93)) # False
print(myList.search(12)) # True
print(myList.getAllData())
myList.remove(12)
print(myList.getAllData())