散列技术之链地址法(基于无序链表)
源码例如以下:
#include <stdlib.h> #include <stdio.h> #define hash(v,M) (v % M) typedef char Key; struct Item{ Key key; }; typedef struct STnode* link; struct STnode{ Item item ; link next; }; static link* heads , z ; static struct Item NULLitem ; static int N , M ; Key key(Item item){ return item.key; } //创建一个节点 static link NEW(Item item, link next){ link x = (link)malloc(sizeof *x); x->item = item;x->next = next; return x; } //初始化 void STinit(int max){ int i ; N = 0; M = max / 5; heads = (link *)malloc(M*sizeof(link)); z = NEW(NULLitem,NULL); for(i=0;i<M;i++)heads[i] = z; } //节点个数 int STcount(){ return N; } //搜索子程序 Item searchR(link h, Key v){ Key t = key(h->item); if(h==z)return NULLitem; if(v==t) return h->item; return searchR(h->next,v); } //搜索主程序 Item STsearch(Key v){ return searchR(heads[hash(v,M)],v); } //插入主程序 void STinsert(Item item){ int i = hash(key(item),M) ; heads[i] = NEW(item,heads[i]); N++; } //单链表删除指定的节点 非递归 link deleteT(link head,Item v){ link node1=head; link node2=NULL; if (head==NULL)return NULL; if (node1->item.key==v.key){ head=head->next; free(node1); return head; } while (node1!=NULL){ node2=node1; node2=node2->next; if (node2->item.key==v.key){ node1->next=node2->next; free(node2); break; } node1=node1->next; } return head; } //单链表删除指定的节点 递归 link deleteR(link h,Item item){ if(h==NULL)return NULL; if(key(h->item) == key(item))return h->next; h->next = deleteR(h->next,item); return h; } void STdelete(Item item){ int i = hash(key(item),M) ; heads[i] = deleteR(heads[i],item); } void p(link h){ link t = h; while(t!=NULL){ printf("%c ",key(t->item)); t = t->next; } printf("\n"); } main(){ STinit(26); 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]); for(i = 0; i<M;i++) p(heads[i]); printf("search: %c \n",key(STsearch('e'))); struct Item delItem = {'a'}; STdelete(delItem); for(i = 0; i<M;i++) p(heads[i]); }
执行结果