Search code examples
c++linked-listdelete-operator

Delete operator


void createnode(int data)
{
    node *temp=new node;
    temp->data=data;
    if(head==null)
    {
        head=temp;
        tail=temp;
        temp=null;
    }
    else
    {
        tail->next=temp;
        temp=null;
    }
}

Should I delete temp right now? I'll be using another function to delete every node. Will that be enough?


Solution

  • First of all, temp is null, so deleting it would be a no-op.

    If you're asking whether you should delete the result of new node in this function, the answer is "no, you should not". If you did, the list would retain dangling pointers. The correct way is delete the node when it's being removed from the list, when the list itself is being deleted, etc.