- #include <stdio.h>
- #include <stdlib.h>
- typedef int KeyType;
- typedef int DataType;
- typedef struct
- {
- KeyType key;
- DataType value;
- } DicElement;
- typedef struct
- {
- int m;
- DicElement *element;
- } HashDictionary;
- typedef HashDictionary * PHashDictionary;
- ///散列表的初始化。
- PHashDictionary createEmptyDictionary(int m)
- {
- int i;
- PHashDictionary phd = (PHashDictionary)malloc(sizeof(HashDictionary));
- if(phd != NULL){
- phd -> element = (DicElement *)malloc(sizeof(DicElement) * m);
- if(phd ->element != NULL)
- {
- phd ->m = m;
- for(i = 0; i < m; i++)
- phd -> element[i].key = 0;
- return phd;
- }
- else
- free(phd);
- }
- printf("Out of Space!/n");
- return NULL;
- }
- ///散列函数。
- int h(KeyType key)
- {
- return key % 13;
- }
- ///用先性探查法解决碰撞。
- int linearSearch(HashDictionary *phash, KeyType key, int *position)
- {
- int d, inc;
- d =h(key);
- for(inc = 0; inc < phash ->m; inc ++){
- if(phash ->element[d].key == key){
- *position = d;
- return 1;
- }
- else if(phash ->element[d].key == 0){
- *position = d;
- return 0;
- }
- d = (d + 1)%phash ->m;
- }
- *position = -1;
- return 0;
- }
- int main(int argc, char **argv)
- {
- PHashDictionary phd = createEmptyDictionary(13);
- int position = 0;
- printf("%d/t%d/t%d/nposition = %d/n", position, phd ->element[9].key, phd->element[0].value, linearSearch(phd, 123, &position));
- printf("d = %d/n", position);
- return 0;
- }
字典的散列法表示。
最新推荐文章于 2021-08-30 21:03:45 发布