哈希表的实现
1.哈希表的声明文件
//静态哈希表 #pragma once #define MAX_SIZE 10 typedef int DateType; typedef enum { EXIST, EMPTY, DELET }state; //哈希表中的每一个节点 typedef struct HTElem { DateType _data; state _state; }HETlem; //一个哈希表 typedef struct HashTable { HETlem _array[MAX_SIZE]; int _size; //哈希表中的有效元素的个数 int _total; //哈希表中总元素的个数,包括数据和状态 int _IsLineDetective; //是否是线性探测 int _capacity; //哈希表的容量 }HT;
2.哈希表的定义函数文件
#include<stdio.h> #include<Windows.h> #include<assert.h> #include"hashS.c"; int hashfunc(DateType data) // 获得哈希表的地址 { return data % MAX_SIZE; } int DetectiveLine(int hashAdder) //哈希表的线性探测 { hashAdder++; if (hashAdder == MAX_SIZE) { hashAdder = 0; } return hashAdder; } //初始化哈希表 void HashTableInit(HT* ht, int capacity, int IsLineDetective) { int i = 0; for (; i < MAX_SIZE; i++) { ht->_array[i]._state = EMPTY; } ht->_size = 0; ht->_total = 0; ht->_capacity = capacity; ht->_IsLineDetective = IsLineDetective; } //哈希表的插入 void HashTableInsert(HT* ht, DateType data) { int hashadder = 0; int i = 0; assert(ht); if (ht->_total == MAX_SIZE) return; hashadder = hashfunc(data); while (EMPTY != ht->_array[hashadder]._state) { if (EXIST == ht->_array[hashadder]._state) { if (ht->_array[hashadder]._data == data) return; //因为已经有了相同的元素 } if (ht->_IsLineDetective) hashadder = DetectiveLine(hashadder); } ht->_array[hashadder]._data = data; ht->_array[hashadder]._state = EXIST; ht->_size++; ht->_total++; } //哈希表的查找(返回地址) int hashtablefind(HT* ht,DateType data) { int hashadder = -1, staradder = -1; int i = 0; assert(ht); hashadder = hashfunc(data); staradder = hashadder; while (EMPTY != ht->_array[hashadder]._state) { if (EXIST == ht->_array[hashadder]._state) if (data == ht->_array[hashadder]._data) return hashadder; if (ht->_IsLineDetective) { hashadder = DetectiveLine(hashadder); if (hashadder == staradder) return -1; } return -1; } } //哈希表的删除 void hashtabledelete(HT* ht, DateType data) { int ret = -1; assert(ht); ret = hashtablefind(ht, data); if (ret != -1) { ht->_array[ret]._state = DELET; ht->_size--; } } int hashtablesize(HT* ht) { return ht->_size; } int hashtableempty(HT* ht) { return 0 == ht->_size; } void printhashbucket(HT* ht) { int i = 0; for (; i < ht->_size; i++) { if (EXIST == ht->_array[i]._state) { printf("哈希表的地址是%d数据为:%d\n", i, ht->_array[i]._data); } } }
3.哈希表的主函数
#include"hashS.c"; int main(void) { HT ht; HashTableInit(&ht, 10, 1); HashTableInsert(&ht, 21); HashTableInsert(&ht, 15); HashTableInsert(&ht, 16); HashTableInsert(&ht, 13); HashTableInsert(&ht, 27); HashTableInsert(&ht, 10); HashTableInsert(&ht, 34); printhashbucket(&ht); printf("哈希表的size是:%d\n", ht._size); hashtabledelete(&ht, 13); printhashbucket(&ht); printf("哈希表的size是:%d\n", ht._size); system("pause"); return 0; }
计算机小白记录学习过程,喜欢就点个推荐和关注吧O(∩_∩)O哈哈~

浙公网安备 33010602011771号