散列表(哈希表)之链接法浅谈

来源:互联网 发布:慧眼文字识别软件 编辑:程序博客网 时间:2024/04/29 08:57

通俗意义上说,哈希表就是一个数组,每个数组元素存放的是链表的头结点。其作用是将全局域U中的所有元素m个映射到数组元素个数为n(n

头文件中的内容struct hash_node{    int data;    hash_node *next,*prev;};int Hash(int key);void CreateHash(hash_node *hash[],vector<int> &coll);//total为要建立hash表元素的总数void Print(hash_node *hash[]);
#include"hash.h"#define len 7int Hash(int key){    return key%len;}void CreateHash(hash_node *hash[],vector<int> &coll)//total为要建立hash表元素的总数{    int i=0;    int low=0;//hash表中的下标    int total=coll.size();    while(i<total)    {        low=Hash(i);        hash_node *temp=new hash_node();        temp->data=coll[i];        temp->next=NULL;        temp->prev=NULL;        if(hash[low]==NULL)//处理冲突        {            hash[low]=temp;        }        else        {            temp->next=hash[low];//头插法            hash[low]->prev=temp;            hash[low]=temp;        }        ++i;    }}void Print(hash_node *hash[]){    hash_node *temp=NULL;    for(int i=0;i<7;++i)    {         if(hash[i]==NULL)         {             cout<<"the "<<i<<"th number is NULL"<<endl;         }         else         {             cout<<"the "<<i<<"th number is ";             temp=hash[i];             do             {                 cout<<temp->data<<' ';             }while((temp=temp->next) && temp!=NULL);             cout<<endl;         }    }}

哈希表有很好的性能,如果哈希表中元素个数与全局域的元素数成正比,通过计算可得,查找其中一个元素的平均时间复杂度为O(1),当采用双向链表的时候,最坏情况下的时间复杂度为O(1),因为以O(1)找到该元素以后,双向链表插入和删除该元素的时间为常数,此时,全部字典的操作在平均情况下复杂度就为O(1);注意:单链表不是,单链表的插入和删除一个元素的时间复杂度为O(n),因为该节点不知道其前驱节点,所以要遍历才知道,遍历的复杂度就为O(n)。

1 0
原创粉丝点击