Implementation of LinkedList in Python
Implementation of LinkedList in Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def InsertAtBeg(self,data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def InsertAtIndex(self,index,data):
if index < 1:
InsertAtBeg(data)
return
position = 0
current_node = self.head
while current_node.next is not None and position + 1 != index:
position+=1
current_node = current_node.next
if current_node is not None:
new_node = Node(data)
new_node.next = current_node.next
current_node.next = new_node
else:
print("Index is Not Present")
def InsertAtEnd(self,data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
# new_node.next = None # no need
current_node = self.head
while current_node.next:
current_node = current_node.next
current_node.next = new_node
# new_node.next = None #NO need
def DelAtBeg(self):
if self.head == None:
return
self.head = self.head.next
def DelAtLast(self):
if self.head == None:
return
current_node = self.head
while current_node.next and current_node.next.next:
current_node = current_node.next
current_node.next = None
def DelAtIndex(self,index):
position = 0
current_node = self.head
while current_node.next is not None and position + 1 != index:
position+=1
current_node = current_node.next
if current_node is not None and current_node.next.next is not None:
current_node.next = current_node.next.next
else:
print("Index not Found!")
def DelNode(self, data):
current_node = self.head
if current_node is not None and current_node.data == data:
self.DelAtBeg()
return
while current_node is not None and current_node.next is not None:
# current_node = current_node.next
if current_node.data == data:
current_node.next = current_node.next.next
return
current_node = current_node.next
print(" Data is not Found! ")
def lenOf(self):
count = 0
current_node = self.head
while current_node is not None:
count+=1
current_node = current_node.next
return count
def printt(self):
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
l = LinkedList()
l.InsertAtBeg(10)
l.InsertAtIndex(1,20)
l.InsertAtIndex(3,40)
l.InsertAtIndex(4,50)
l.InsertAtIndex(2,30)
l.InsertAtEnd(60)
print(l.lenOf())
print("__________________")
l.printt()
l.DelAtIndex(2)
print(l.lenOf())
print("__________________")
l.printt()
l.DelNode(30)