Why we initialize the next pointer of Linked List as NULL before deletion

332 Views Asked by At

Why we initialize the next pointer of Linked List as NULL before deletion we move our head to the next node during deletion and we free the memory of the first node, so why we need to initialize the next pointer of deleted node as NULL before deletion. without it, the code runs without any issues. Is this dangling pointer will create a issue? please throw some light in it

class Node
{
    public:
    int data;
    Node* next;
    
    Node(int d)     //construtor for storing the value in nodes
    {
        this->data=d;
        this->next=NULL;
    }
};
void DeleteAt(int position,Node* &head,Node *&tail)
{
    if(position ==1)
    {   
        Node* temp=head;
        head=temp->next;
        temp->next=NULL;
        delete temp;
    }
    else
    {
        Node *curr=head;
        Node *prev=NULL;
        int cnt=1;
        while(cnt<position)
        {
            prev=curr;
            curr=curr->next;
            cnt++;
        }
        // if delete at tail is called ,for updation of tail,
        //if required
        if(curr->next==NULL)
        {
            tail=prev;
        }
        prev->next=curr->next;
        curr->next=NULL;
        delete curr;
    }
}
1

There are 1 best solutions below

5
CoffeeTableEspresso On

You don't need to do this, it's just to help you while you're learning. It's common for teachers to do this to help avoid use-after-frees. This way, it's much more obvious you have a problem, because if you accidentally try to use the node you just deleted, you'll probably get a segfault.