散列技术之线性探测法

来源:互联网 发布:2016淘宝有前景的类目 编辑:程序博客网 时间:2024/04/30 21:04

源代码如下:


#include <stdlib.h>#include <stdio.h>#define hash(v,M) (v % M)#define null(A) (key(st[A]) == key(NULLitem)) typedef char Key;struct Item{Key key;};static struct Item NULLitem ;static struct Item *st;static int N , M ;Key key(Item item){return item.key;}//初始化 void STinit(int max){int i ;N = 0; M = 2 * max;st = (Item *)malloc(M*sizeof(Item));for(i=0;i<M;i++)st[i] = NULLitem;}//节点个数 int STcount(){return N; } //搜索主程序 Item STsearch(Key v){int i = hash(v,M) ;while(!null(i))if(v == key(st[i]))return st[i];else i = (i+1) & M;return NULLitem;}//插入主程序 void STinsert(Item item){int i = hash(key(item),M) ;printf("%d %d %d\n",key(item),M, i) ;while(!null(i)) i = (i+1) & M;st[i] = item; N++;}//删除主程序void STdelete(Item item){int j, i = hash(key(item),M) ; Item v;while(!null(i))if(key(item) == key(st[i]))break;else i = (i+1) & M;st[i] = NULLitem; N--;for(j = i+1;!null(j);j=(j+1)%M,N--){v = st[j]; st[j] =NULLitem; STinsert(v);}}void p(){struct Item *tmp = st;int i ;for(i=0;i<M;i++)if(!null(i)) printf("%c ",key(st[i]));printf("\n");}main(){STinit(13);struct Item item[13] ={'a','s','e','r','c','h','i','n','g','x','m','p','l'};int i;for(i = 0; i<13;i++)STinsert(item[i]);p();printf("search: %c \n",key(STsearch('e')));STdelete(item[10]);p();}


运行结果




0 0