Python Program For Deleting A Node In A Doubly Linked List
Last Updated :
18 May, 2022
Pre-requisite: Doubly Link List Set 1| Introduction and Insertion
Write a function to delete a given node in a doubly-linked list.Â
Original Doubly Linked ListÂ
Approach: The deletion of a node in a doubly-linked list can be divided into three main categories:Â
- After the deletion of the head node.Â
- After the deletion of the middle node.Â
- After the deletion of the last node.
All three mentioned cases can be handled in two steps if the pointer of the node to be deleted and the head pointer is known.Â
- If the node to be deleted is the head node then make the next node as head.
- If a node is deleted, connect the next and previous node of the deleted node.
AlgorithmÂ
- Let the node to be deleted be del.
- If node to be deleted is head node, then change the head pointer to next current head.
if headnode == del then
headnode = del.nextNode
- Set next of previous to del, if previous to del exists.
if del.nextNode != none
del.nextNode.previousNode = del.previousNode
- Set prev of next to del, if next to del exists.
if del.previousNode != none
del.previousNode.nextNode = del.next
Python
import gc
class Node:
def __init__( self , data):
self .data = data
self . next = None
self .prev = None
class DoublyLinkedList:
def __init__( self ):
self .head = None
def deleteNode( self , dele):
if self .head is None or dele is None :
return
if self .head = = dele:
self .head = dele. next
if dele. next is not None :
dele. next .prev = dele.prev
if dele.prev is not None :
dele.prev. next = dele. next
gc.collect()
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
if self .head is not None :
self .head.prev = new_node
self .head = new_node
def printList( self , node):
while (node is not None ):
print node.data,
node = node. next
dll = DoublyLinkedList()
dll.push( 2 );
dll.push( 4 );
dll.push( 8 );
dll.push( 10 );
print "Original Linked List" ,
dll.printList(dll.head)
dll.deleteNode(dll.head)
dll.deleteNode(dll.head. next )
dll.deleteNode(dll.head. next )
print "Modified Linked List" ,
dll.printList(dll.head)
|
Output:Â
Original Linked list 10 8 4 2
Modified Linked list 8
Complexity Analysis:Â
- Time Complexity: O(1).Â
Since traversal of the linked list is not required so the time complexity is constant.
- Space Complexity: O(1).Â
As no extra space is required, so the space complexity is constant.
Please refer complete article on Delete a node in a Doubly Linked List for more details!
Share your thoughts in the comments
Please Login to comment...