散列表进行插入和删除都要借助于hash函数,根据要插入或删除的值,对应到相应的位置,再对该位置进行操作。代码如下:
void collsion(hash_node *hash[],int elem, hash_node *news)//*hash[]传的是指针数组,其实传的是指针数组的首地址,即地址的地址,如果直接传数组元素的地址,返回并不指向该数组中元素的地址。处理冲突
{
if(hash[elem]==NULL)
{
hash[elem]=news;
}
else
{
news->next=hash[elem];//头插法,elem是数组元素下标,即该下标 链表的头结点
hash[elem]->prev=news;
hash[elem]=news;
}
}
void Insert(hash_node *hash[],int key)
{
hash_node *temp=new hash_node();
temp->data=key;
temp->next=NULL;
temp->prev=NULL;
int location=Hash(key);//此位置就是随机的,根据key的值来得到它的位置
collsion(hash,location,temp);//location元素下标,即头结点
}
void Delete(hash_node *hash[],int key)
{
int low=Hash(key);
hash_node *temp=hash[low];
if(temp==NULL)
{
cout<<"this number doesn't exit!"<<endl;
return;
}
else
{
if(temp->data==key)//预防第一个就找到该值
{
hash[low]=temp->next;
delete temp;
return;
}
else
{
while(temp->data!=key)
{
if(temp->next==NULL)
{
cout<<"this number isn't found"<<endl;
return;
}
temp=temp->next;
}
if(temp->next==NULL)//预防是最后一个找到该值
{
temp->prev->next=NULL;
delete temp;
}
else
{
temp->prev->next=temp->next;
temp->next->prev=temp->prev;
delete temp;
}
}
}
}
由此可知,插入操作时间复杂度就是O(1),删除操作的时间复杂度可根据链表输入长度决定,在最坏情况下,链表长度为n,时间复杂度就为o(n).