Reputation: 31
Below is a delete node in Linklist code that takes head pointer and position to delete as arguments (position index start at ZERO in Linklist). And after deleting, returns a pointer to head.
Node* delete(Node* head, int position)
{
Node *p = head;
if(!position)
{
p = p->next;
}
else
{
while(position--)
{
if(!position) head->next = head->next->next;
head = head->next;
}
}
free(head);
return p;
}
Suppose list: 20-2-19-7-3-6. And position to delete is 2 (node 19 to delete, since index start from zero).
After deleting, and printing, it says: 20-2-0-3-6.(i.e. the node directly next to the one deleted prints 0)
But if I remove the line "free(head)", then it prints: 20-2-7-3-6 (correctly).
Please help and explain why.
PS: There is no issue when deleting head node or tail node. But any other node in between shows 0 in next node.
Upvotes: 1
Views: 618
Reputation: 503
This is the dry run of the code:
20 --> 2 --> 19 --> 7 --> 3 --> 6
^
head
while(position--) // position == 2
{
if(!position) // position == 1, condition is false
head->next = head->next->next;
head = head->next;
}
20 --> 2 --> 19 --> 7 --> 3 --> 6
^
head
while(position--) // position == 1
{
if(!position) // position == 0, condition is true
head->next = head->next->next;
head = head->next;
}
/-----\
20 --> 2 --/ 19 --> 7 --> 3 --> 6 // 2's next is pointing to 7 now
^
head
Now free(head)
will be executed which will delete the node containing number 7
. Now, when you print, you'll probably get:
20 -> 2 -> (reference to deleted node) -> 3 -> 6
I think this is undefined behavior that you are referencing the deleted node and it's printing 0
.
Upvotes: 2