Delete a node from the end of doubly linked list in python
Python program for Delete a node from the end of doubly linked list. Here problem description and explanation.
# Python 3 program for
# Delete a node from the end of doubly linked list
class LinkNode :
def __init__(self, data) :
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList :
def __init__(self) :
self.head = None
self.tail = None
# Insert new node at end position
def insert(self, value) :
# Create a node
node = LinkNode(value)
if (self.head == None) :
# Add first node
self.head = node
self.tail = node
return
# Add node at last position
self.tail.next = node
node.prev = self.tail
self.tail = node
# Display node element of doubly linked list
def display(self) :
if (self.head == None) :
print("Empty Linked List")
else :
print("\nLinked List Head to Tail : ")
# Get first node of linked list
temp = self.head
# iterate linked list
while (temp != None) :
# Display node value
print("", temp.data, end = " ")
# Visit to next node
temp = temp.next
# Remove the given node from end of linked list
def deletionFromEnd(self, key) :
if (self.head == None) :
# Empty linked list
return
auxiliary = None
temp = self.tail
# Find the deleted node
while (temp != None and auxiliary == None) :
if (temp.data == key) :
# We found deleted node
auxiliary = temp
# Visit to previous node
temp = temp.prev
if (auxiliary != None) :
# When we get deleted node
if (auxiliary.prev != None) :
# When previous node present
auxiliary.prev.next = auxiliary.next
if (auxiliary.next != None) :
# When next node present
auxiliary.next.prev = auxiliary.prev
if (self.head == auxiliary) :
# When delete head node
self.head = self.head.next
if (auxiliary == self.tail) :
# When delete last node
self.tail = self.tail.prev
auxiliary = None
else :
print("\nNode not exist ", key)
def main() :
dll = DoublyLinkedList()
# Insert following linked list nodes
dll.insert(1)
dll.insert(2)
dll.insert(9)
dll.insert(4)
dll.insert(5)
dll.insert(2)
dll.insert(7)
dll.insert(9)
print("\nBefore Delete", end = "")
dll.display()
key = 2
dll.deletionFromEnd(key)
print("\nAfter Delete Node ", key, end = "")
dll.display()
if __name__ == "__main__": main()
Output
Before Delete
Linked List Head to Tail :
1 2 9 4 5 2 7 9
After Delete Node 2
Linked List Head to Tail :
1 2 9 4 5 7 9
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment