散列表的插入和删除

散列表进行插入和删除都要借助于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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值