搬运自我的CSDN https://blog.csdn.net/u013213111/article/details/88870924
1.定义
在开放定址法中,用一个数组来存储散列表的元素,因此散列表结构Htable中有一个数组(指针)CellArray,数组中的每一个元素都是一个Hcell,Hcell中除了有data外,还有一个enum类型的字段来记录该元素的“状态”,为空、被使用或者已删除。
1 enum entrykind {Legitimate, Empty, Deleted}; 2 3 typedef struct cell 4 { 5 eletype data; 6 enum entrykind info; 7 }Hcell; 8 9 typedef struct table 10 { 11 int size; 12 Hcell *CellArray; 13 }Htable;
2.新建一个散列表
注意要将数组CellArray中的每一个元素的状态info设置为Empty。
1 Htable *CreateHashTable(int tsize) 2 { 3 Htable *H; 4 5 if (tsize < MinSize) { 6 printf("Table size must >= %d\n", MinSize); 7 return NULL; 8 } 9 10 H = malloc(sizeof(Htable)); 11 if (H == NULL) { 12 printf("Create table failed\n"); 13 return NULL; 14 } 15 16 H->size = NextPrime(tsize); 17 H->CellArray = malloc(sizeof(Hcell) * H->size); 18 if (H->CellArray == NULL) { 19 printf("Out of space\n"); 20 return NULL; 21 } 22 23 Hcell *pcell; 24 pcell = H->CellArray; 25 for (int i = 0; i < H->size; i++) { 26 pcell->info = Empty; 27 pcell++; 28 } 29 30 return H; 31 }
3.插入
用到的Find和Hash函数与写给自己看的散列表(1):分离链接法中相同,特别点在于将info设置为Legitimate,表示该存储空间被使用了。
1 void Insert(Htable *H, eletype key) 2 { 3 uint pos; 4 pos = Find(H, key); 5 if (H->CellArray[pos].info != Legitimate) { 6 H->CellArray[pos].info = Legitimate; 7 //strcpy(H->CellArray[pos].data, key); 8 H->CellArray[pos].data = key; 9 } 10 }
原文:https://www.cnblogs.com/lyrich/p/10800466.html