#include<iostream> #define M 30 //定义hash表的大小 #define NULLDATA -1 #define H(A) (A%M ) //除余法hash函数 using namespace std; typedef struct node *link; typedef struct node { int data; link next; }node; link Table[M]; link p[M]; //辅助插入指针 static int k; //统计查找元素所需时间 void Init() //初始化 { for(int i = 0; i < M; i++) { Table[i] = NULL; } } link newnode(int v) { link c = (node *)malloc(sizeof(node)); c->data = v; c->next = NULL; return c; } void Insert(int v) { int i = H(v); if(Table[i] == NULL) { p[i] = newnode(v); Table[i] = p[i]; } else { p[i]->next = newnode(v); p[i] = p[i]->next; } } int find_list(link h,int v) //slot中的查找操作 { while(h->data != v && h->next != NULL) { h = h->next; k++; } if(h->next == NULL) return NULLDATA; else return h->data; } int find(int v) //Table查找操作 { int tmp; int j = H(v); if(Table[j] != NULL) tmp = find_list(Table[j],v); else return NULLDATA; return tmp; } int Delete_list(link h, int v) //删除slot中的元素 { link aux; int tmp; while(h->data != v) { aux = h; h = h->next; } aux->next = h->next; tmp = h->data; return tmp; } int Delete(int v) //Table删除操作 { int j = H(v); int tmp; if(Table[j] != NULL) tmp = Delete_list(Table[j],v); else return NULLDATA; return tmp; } int main() { Init(); for(int i = 0; i < 10000; i++) Insert(i); cout<<find(33)<<endl; cout<<Delete(33)<<endl; cout<<find(9967)<<endl; cout<<k<<endl; return 0; }
查找时间为:(1+a) a为装载因子。分析见导论P135~136。