-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedList.py
105 lines (88 loc) · 2.63 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
94
95
96
97
98
99
100
101
102
103
104
105
"""
Node class has the data and a pointer that is used to point to the next Node object.
"""
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self, next_node):
self.next_node = next_node
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def insertFront(self, data):
new_node = Node(data)
new_node.set_next(self.head)
self.head = new_node
def append(self, data):
new_node = Node(data)
if self.head == None:
self.head = new_node
else:
current = self.head
while current.get_next():
current = current.get_next()
current.set_next(new_node)
def size(self):
current = self.head
count = 0
while current:
count += 1
current = current.get_next()
return count
def search(self, data):
current = self.head
if current == None:
return "No elements present to search. Please insert elements first."
found = False
while current and found == False:
if current.get_data() == data:
found = True
else:
current = current.get_next()
if current == None:
return "Value not found"
return "Match Found"
def delete(self, data):
current = self.head
if current == None:
return "No elements present to delete. Please insert elements first."
found = False
prev = None
while current and found == False:
if current.get_data() == data:
found = True
else:
prev = current
current = current.get_next()
if current == None:
return "Value not found"
if prev == None:
self.head = current.get_next()
else:
prev.set_next(current.get_next())
return "Successfully deleted " + str(data)
def printElements(self):
current = self.head
if current == None:
print "No elements present. Please insert elements."
return
while current:
print current.get_data()
current = current.get_next()
#Test
list = LinkedList()
list.printElements()
print list.delete(5)
list.append(4)
list.append(5)
list.append(6)
list.append(7)
list.printElements()
print list.delete(7)
list.printElements()
print list.size()