-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked_List.py
90 lines (71 loc) · 2.41 KB
/
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#===================================================
""" Linked List Implementation in PYTHON """
#===================================================
class Node(object):
def __init__(self, data=None, next=None):
self.data = data # contains the data
self.next = next # contains the reference
def __str__(self):
return str(self.data) # prints the data
class LinkedList(object):
def __init__(self):
self.head = None
self.size = 0
def isEmpty(self):
if self.head == None:
return True
else:
return False
def insert_first(self, data):
'''inserts the new Node at the start of the list'''
new_node = Node(data, self.head)
self.head = new_node #here, making new node as new head
self.size += 1
def delete(self, data):
'''
# Start from the Root node
# Check if root matches the data;
then shift the root to the root.next
else mode to the next node
# else move to the next node;
if match found, point the prev node to the node next to current
'''
current = self.head #start for the root/head
prev_node = None
while current:
if current.data == data:
if prev_node: #means current is NOT a root node
prev_node.next = current.next
else:
#current is the root node
self.head = current.next
self.size -=1
return True #node found
else:
prev_node = current
current = current.next
#if node is not found inside while loop
return False
def printList(self):
current = self.head
while current:
print(str(current.data) + "-->",end="")
current = current.next
print("NULL")
def get_size(self):
print("LinkedList size: " + str(self.size))
if __name__ == "__main__":
a = LinkedList()
a.insert_first(10)
a.insert_first(20)
a.insert_first(30)
a.printList()
a.get_size()
a.delete(10)
a.printList()
print(a.isEmpty())
a.delete(20)
a.printList()
a.delete(30)
a.printList()
print(a.isEmpty())