enh(Python): add insert end function on singly linked list (#700)
Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com>pull/704/head
parent
27cfae8f52
commit
7b07f177b9
|
@ -78,6 +78,58 @@ class LinkedList:
|
|||
raise IndexError("pop from empty LinkedList")
|
||||
self.head = node.next
|
||||
return node.data
|
||||
|
||||
def insertEnd(self, data):
|
||||
'''
|
||||
Insert node at the end of linked list
|
||||
'''
|
||||
node = Node(data)
|
||||
if self.head is None:
|
||||
self.head = node
|
||||
return
|
||||
|
||||
# Linked list traversal
|
||||
temp = self.head
|
||||
while(temp.next is not None):
|
||||
temp = temp.next
|
||||
|
||||
temp.next = node
|
||||
return
|
||||
|
||||
def deleteData(self, data):
|
||||
'''
|
||||
Delete first occurrence of given data
|
||||
'''
|
||||
temp = self.head
|
||||
|
||||
# raise exception if linked list is empty
|
||||
if temp is None:
|
||||
raise Exception("Linked List is empty")
|
||||
|
||||
# if head node is deleted
|
||||
if temp.data == data:
|
||||
self.head = temp.next
|
||||
temp = None
|
||||
return
|
||||
|
||||
# search for data
|
||||
# previous node data is stored
|
||||
while(temp):
|
||||
found = False
|
||||
if temp.data == data:
|
||||
found = True
|
||||
break
|
||||
prev = temp
|
||||
temp = temp.next
|
||||
|
||||
# raise exception if data not found
|
||||
if not found:
|
||||
raise Exception("Data not present")
|
||||
|
||||
# delete the link
|
||||
prev.next = temp.next
|
||||
temp = None
|
||||
return
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
@ -86,5 +138,8 @@ if __name__ == '__main__':
|
|||
ll.push('xyz')
|
||||
ll.push(1.1)
|
||||
ll.pop()
|
||||
ll.insertEnd('END')
|
||||
print(ll)
|
||||
ll.deleteData(1)
|
||||
print(ll)
|
||||
print(list(ll))
|
||||
|
|
Loading…
Reference in New Issue