I am working on the GeeksForGeeks problem Delete node in Doubly Linked List:
Given a doubly linked list and a position. The task is to delete a node from given position in a doubly linked list.
Your Task:
The task is to complete the function
deleteNode()
which should delete the node at given position and return the head of the linkedlist.
My code:
def deleteNode(self,head, x):
# Code here
temp=head
count_of_nodes=0
prev_of_delete_node=None
next_of_delete_node=None
while temp != head:
count_of_nodes =1
if count_of_nodes==x:
prev_of_delete_node=temp.prev
next_of_delete_node=temp.next
#print(y.data,z.data)
prev_of_delete_node.next=next_of_delete_node
next_of_delete_node.prev=prev_of_delete_node
break
temp=temp.next
if x==1:
head=next_of_delete_node
There is no effect on the doubly LinkedList after executing above code. Why is this?
CodePudding user response:
Some issues:
The
while
condition is wrong: it is false immediately, so the loop will not execute.The value for
prev_of_delete_node
could beNone
when you dereference it withprev_of_delete_node.next
. So guard that operation. Same fornext_of_delete_node
.The function doesn't return anything, but it should return the head of the list after the deletion
Correction:
def deleteNode(self,head, x):
temp=head
count_of_nodes=0
prev_of_delete_node=None
next_of_delete_node=None
while temp: # Corrected loop condition
count_of_nodes =1
if count_of_nodes==x:
prev_of_delete_node=temp.prev
next_of_delete_node=temp.next
if prev_of_delete_node: # Guard
prev_of_delete_node.next=next_of_delete_node
if next_of_delete_node: # Guard
next_of_delete_node.prev=prev_of_delete_node
break
temp=temp.next
# Should return:
if x==1:
return next_of_delete_node
return head