Hashing erase function

sir I tried this function but facing some problem . can u plzz help me how to proceed further or whether it is correct or not
T *erase(string key)
{
int i=hashfn(key);
node*temp=buckets[i];
if(temp==NULL)
{
return;
}
if(temp->key==key)
{
if((temp->next)!=NULL)
{
node*prev=temp->next;
buckets[i]=prev;
delete(temp);
}
}
while(temp!=NULL)
{
if(temp->next->key==key)
{
node*prev=temp->next;
temp=temp->next->next;
delete(prev);
}
temp=temp->next;
}
}

Hello @khushi91200,

Please, explain the logic that you have applied.

Are you implementing a function to delete a particular key-value pair from the hash table?

yes sir to delete a particular key value pair

Hello @khushi91200,

Let’s debug your code:

  1. The return type of this function?
    Your code isn’t returning anything. It would cause an error.
    And you have take T as return type.

  2. The following modification will work for the case when there is only one element in the list:

if(temp->key==key)
{
node*prev=temp->next;
buckets[i]=prev;
delete(temp);
}

There is no need for the conditional check.

  1. Modifications Required:
//Solution to Problem 1.

//Execute till temp->next!=NULL
while(temp!=NULL)
{
//Problem 1
//It will give runtime-error for the case when temp is the last element:
//for that element, temp->next=NULL
//Thusthere is no temp->next->key
if(temp->next->key==key)
{
node*prev=temp->next;
//Modification: temp->next=temp->next->next
//It is similar to deletion in linked list from middle
temp=temp->next->next;
delete(prev);
//Add break;
}
temp=temp->next;
}
//Write a code to check if the last element is the required element that is required to be deleted.

Hope, this would help.
Give a like, if you are satisfied.

1 Like

void erase(string key)
{
int i=hashFn(key);
nodetemp=buckets[i];
if(temp->key==key)
{
node
prev=temp->next;
buckets[i]=prev;
delete(temp);
return;
}
while(temp->next!=NULL)
{
if(temp->next->key == key)
{
node*prev=temp->next;
temp->next=temp->next->next;
delete(prev);
return;
}
temp=temp->next;
}
}
sir I tried this but still facing problem

Hello @khushi91200,

I apologise for replying late.
I was stuck in some emergency situation.

Can you please share your entire code?
Also, Share it using Online Coding blocks IDE.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.