forked from devAmoghS/Python-Interview-Problems-for-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list_data_structure.py
66 lines (55 loc) · 1.47 KB
/
linked_list_data_structure.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
class Node:
def __init__(self, data=None):
self.data = data
self.next_node = None
def getData(self):
return self.data
def setData(self, data):
self.data = data
def getNextNode(self):
return self.next_node
def setNextNode(self, new_next):
self.next_node = new_next
class LinkedList:
def __init__(self, head=None):
self.head = head
def isEmpty(self):
return self.head == None
def insert(self, data):
temp = Node(data)
temp.setNextNode(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current:
count+=1
current.getNextNode()
return count
def search(self, data):
current = self.head
found = False
while current and not found:
if current.getData() == data:
found = True
else:
current = current.getNextNode()
if current is None:
raise ValueError("Data is not in the list")
return current
def delete(self, data):
current = self.head
previous = None
found = False
while current and not found:
if current.getData() == data:
found = True
else:
previous = current
current = current.getNextNode()
if current is None:
raise ValueError("Data is not in the list")
if previous is None:
self.head = current.getNextNode()
else:
previous.setNextNode(current.getNextNode())