Created
December 19, 2017 17:20
-
-
Save Madhivarman/b9675f8d361f9d91089d1ada1a13ee59 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
#creation of node | |
def __init__(self,data): | |
self.data = data #assign data | |
self.next = 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 | |
new_data.next = 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 | |
return | |
#traverse till last data to append the data | |
last = self.head | |
while(last.next): | |
last = last.next | |
#change the next of lastnode | |
last.next= new_data | |
def insertafter(self,prev_data,new_data): | |
if prev_data is None: | |
print("The previous node should be in the list") | |
return | |
new_node = Node(new_data) | |
#make previous node next element as new_node next element | |
new_node.next = prev_data.next | |
#make new_node next to the previous element | |
prev_data.next = new_node | |
def delete(self,key): | |
temp = self.head | |
if temp is None: | |
print "There is no data in the linked list to delete" | |
return | |
#if head node itself holds key then delete | |
if(temp is not None): | |
if(temp == key) : | |
self.head = temp.next | |
temp = None | |
return | |
while(temp is not None): | |
if(temp == key): | |
break | |
prev = temp | |
temp = temp.next | |
prev.next = temp.next | |
temp = None | |
def printList(self): | |
temp = self.head | |
while(temp): | |
print temp.data | |
temp = temp.next | |
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(list.head.next,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:' | |
list.printList() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment