I tried to implement erase() function, but it is not correct. I am unable to figure out, what am i doing wrong. Please look in the code and help me understand whats wrong.
Hashtable Class - Erase implementation
at line no 37
correct condition is
if(temp){
temp = temp->next;
}
Modified Code
Additional Point
also while deleting no need to consider 3 cases
all 3 cases can be handled using these statements
like this
void erase(string key){
int idx=hashfun(key);
Node<T>*temp=table[idx];
Node<T>*prev=NULL;
while(temp){
if(temp->key==key){
if(prev)prev->next=temp->next;
else table[idx]=temp->next;
temp->next=NULL;
delete temp;
}
prev=temp;
temp=temp->next;
}
}
Okay. Understood.
But i am unable to get, why ‘if’ condition is not necessary, when we’re doing:-
Will it not show segmentation fault, if temp is NULL?
if condition is necessary
but your condition is wrong
correct condition
if(temp)
temp = temp->next;
Your Condition
if(!temp)
temp = temp ->next;
yes
because NULL->next doesn’t valid