Uploaded by Rashed Roman

Untitled3.ipynb - Colaboratory

advertisement
class Node:
def __init__(self,value,n=None):
self.data = value
self.next = n
a = Node(5)
b = Node(3)
c = Node(9)
# This is not yet a linked list
print(a)
print(a.data)
print(a.next)
print(b.next)
a.next = b
b.next = c
print(b)
print(a.next)
print()
print()
print("Creating a linked list class")
print()
print()
# But this is a manual process. Creating a linked list class can help us make it
# easier and also automate.
class LinkedList:
def __init__(self):
self.head = None
# Number of nodes
self.count = 0
# Insertion
def inserthead(self,value): # Insert from head
# Create a new node
new_node = Node(value)
new_node.next = self.head
# Reassign head
self.head = new_node
self.count += 1
def inserttail(self,value): #Append # But this will not work for empty lists
if self.head == None:
new_node = Node(value)
self.node = new_node
else:
new_node = Node(value)
temp = self.head
while temp.next != None:
temp = temp.next
temp.next = new_node
self.count += 1
def insertmiddle(self,value,after):
new_node = Node(value)
current = self.head
while current != None:
if current.data == after:
break
current = current.next
if current!= None:
new_node.next = current.next
current.next = new_node
else:
print('Element not found')
self.count += 1
def clear(self):
self.head = None
self.count = 0
def deletefromhead(self):
self.head = self.head.next
self.count -= 1
def deletefromtail(self):
if self.head == None:
return 'Empty LL'
current = self.head
if current.next == None:
self.deletefromhead()
else:
while current.next.next != None:
current = current.next
current.next = None
self.count -= 1
def delete_from_value(self, value):
current = self.head
if self.head == value:
self.deletefromhead()
else:
while self.head != value:
current = current.next
current.next = current.next.next
def traverse(self):
current = self.head
result = ''
while current!= None:
result = result + str(current.data) + '->'
current = current.next
print(result[:-2])
def __len__(self):
return self.count
# insertion from head
L = LinkedList()
print(L.head)
print(len(L))
L.inserthead('a')
L.inserthead('b')
L.inserthead('c')
print(len(L))
L.traverse()
L.inserttail('d')
print(len(L))
L.traverse()
L.insertmiddle('e','b')
L.deletefromtail()
L.traverse()
Download