1 #ifndef _HASHTABLE_H_
  2 #define _HASHTABLE_H_
  3 #include <iostream>
  4 #include <cstdlib>
  5 using namespace std;
  6 
  7 typedef
  8 enum {
  9     Empty, Active, Deleted
 10 }kindofitem;
 11 
 12 typedef struct
 13 {
 14     int key;
 15 }datatype;
 16 
 17 typedef struct{
 18     datatype data;
 19     kindofitem info;
 20 }hashitem;
 21 
 22 typedef struct{
 23     hashitem* arr;
 24     int table_size;
 25     int current_size;
 26 }hashtable;
 27 
 28 int initiate(hashtable* hash, int size);//初始化哈希表
 29 int find(hashtable* hash, datatype x);//查找x元素对应的关键字
 30 int insert(hashtable* hash, datatype x);//像哈希表中插入数组元素x,及设置它对应的关键字
 31 int deleted(hashtable* hash, datatype x);//从哈希表中删除x数据元素
 32 void destroy(hashtable* hash);//撤销函数
 33 /*
 34 int main()
 35 {
 36 
 37 system("pause");
 38 return 0;
 39 }
 40 */
 41 int initiate(hashtable* hash, int size)
 42 {
 43     hash->arr = (hashitem*)malloc(sizeof(hashitem)*size);//初始化,该数组
 44     hash->table_size = size;
 45     if (hash->arr == NULL)
 46     {
 47         cout << "初始化失败" << endl;
 48         return 0;
 49     }
 50     else
 51     {
 52         hash->current_size = 0;
 53         return 1;
 54     }
 55 }
 56 
 57 int find(hashtable* hash, datatype x)//查找x元素对应的关键字
 58 {
 59     int i = x.key%hash->table_size;
 60     int j = i;
 61     while (hash->arr[j].info == Active&&hash->arr[j].data.key != x.key)
 62     {
 63         j = (j + 1)&hash->table_size;//用哈希冲突方法继续查找
 64         if (j == i)
 65         {
 66             cout << "遍历此哈希表,没有找到" << endl;
 67             return -hash->table_size;
 68         }
 69     }
 70     if (hash->arr[j].info == Active)
 71     {
 72         return j;
 73     }
 74     else{
 75         return -j;
 76     }
 77 }
 78 
 79 int insert(hashtable* hash, datatype x)
 80 {
 81     int i = find(hash, x);
 82     if (i > 0)
 83     {
 84         cout << "该数据元素已经存在了!" << endl;
 85         return 0;
 86     }
 87 
 88     else if (i != -hash->table_size)
 89     {
 90         hash->arr[-i].data = x;
 91         hash->arr[-i].info = Active;
 92         hash->current_size++;
 93         return 1;
 94     }
 95     else{
 96         return 0;
 97     }
 98 }
 99 
100 int deleted(hashtable* hash, datatype x)
101 {
102     int i = find(hash, x);
103     if (i > 0)
104     {
105         hash->arr[i].info = Deleted;
106         hash->current_size--;
107         return 1;
108     }
109     else{
110         cout << "没有这个元素,无法删除!" << endl;
111         return 0;
112     }
113 }
114 
115 void destroy(hashtable* hash)
116 {
117     delete[]hash->arr;
118 }
119 #endif
hashtable.h

相关文章:

  • 2021-08-02
  • 2021-12-14
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-08
  • 2021-09-07
  • 2021-12-30
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案