please tell why are we deleting the next node in the destructor and why not the current one.
Query regarding destructor
@Parmeet-Kalsi-1631789033630118
first thing you need to know is that the destructor of a class object is invoked when the class object goes out of scope or is deleted using delete (if dynamically allocated ),
Now let’s say we have a linked list {1->2->3->4->5} at some index of hash table ,say .hash[idx] points to the head of that linked list i.e.1 now when hash table goes out of scope then the constructor will be invoked for hash[idx] which is node 1, now if node 1 is deleted only then we will have 2->3->4->5 still remaining in the memory with no pointer leading to them, so we try to delete the entire linked list recursively ,
let’s see the code :-
~Node(){
if(next!=NULL){
delete next;
}
}
here this is an example of recursive destructor
so if we have linked list as 1->2 ->3 ->4 ->5 -> NULL
and when we delete 1 then destructor is invoked for 1 and it checks for its next which is present and is the address for 2 thus invoking destructor of 2 similarly we reach 5 and check for its next which is NULL thus is returned to 4 and 5 is deleted and we return to 3 and 4 is deleted and finally we will be left with 1.
try to dry run it yourself
In case of any doubt feel free to ask
mark your doubt as resolved If you got the answer