Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
class Node:
#creation of node
def __init__(self,data): = data #assign data = None #initialize null
class LinkedList:
#declaring next node as null
def __init__(self):
self.head = None
def push(self,new_data):
new_data = Node(new_data)
#move the head data next to the new data = self.head
#make new data as first data
self.head = new_data
def append(self,new_data):
new_data = Node(new_data)
# if there is no data push the data at first
if self.head is None:
self.head = new_data
#traverse till last data to append the data
last = self.head
last =
#change the next of lastnode new_data
def insertafter(self,prev_data,new_data):
if prev_data is None:
print("The previous node should be in the list")
new_node = Node(new_data)
#make previous node next element as new_node next element =
#make new_node next to the previous element = new_node
def delete(self,key):
temp = self.head
if temp is None:
print "There is no data in the linked list to delete"
#if head node itself holds key then delete
if(temp is not None):
if(temp == key) :
self.head =
temp = None
while(temp is not None):
if(temp == key):
prev = temp
temp = =
temp = None
def printList(self):
temp = self.head
temp =
if __name__ == '__main__' :
list = LinkedList() #create a empty linked list
list.append(6) #append 6->
list.push(1) # 1->6
list.push(2) # 2->1->6
list.insertafter(,8) # 2->1->8->6
list.append(10) # 2->1->8->6->10
list.delete(8) # 2->1->6->10
print 'created linked list is:'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment