散列技術之鏈地址法(基於無序鏈表)
阿新 • • 發佈:2017-06-28
stc 分享 item size obj 單鏈表 結果 clu arc
執行結果
源碼例如以下:
#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]); }
執行結果
散列技術之鏈地址法(基於無序鏈表)