数据结构之散列表查找(哈希表)
这个知识点不难,话不多说,直接上代码.
代码如下:
1 #include "stdafx.h" 2 #include<iostream> 3 #define SUCCESS 1 4 #define UNSUCCESS 0 5 #define HASHSIZE 12 //定义散列表长为数组的长度 6 #define NULLKEY -32768 7 8 using namespace std; 9 10 typedef struct { 11 int *elem; 12 int count; 13 }HashTable; 14 int m = 0; 15 16 int InitHashTable(HashTable &H) //初始化数列表 17 { 18 int i; 19 m = HASHSIZE; 20 H.count = m; 21 H.elem = new int[m]; 22 for (i = 0; i < m; i++) 23 H.elem[i] = NULLKEY; 24 return 1; 25 } 26 27 int Hash(int key) //散列函数 28 { 29 return key % m; //除留余数法 30 } 31 32 void InsertHash(HashTable &H, int key) //求散列地址 33 { 34 int addr = Hash(key); 35 while (H.elem[addr] != NULLKEY) //如果不为空,则冲突 36 addr = (addr + 1) % m; //开放定址法的线性探测 37 H.elem[addr] = key; //知道有空位后插入关键字 38 } 39 40 int SearchHash(HashTable H, int key, int &addr)//散列表查找关键字 41 { 42 addr = Hash(key); //求散列地址 43 while (H.elem[addr] != key) //如果不为空,则冲突 44 { 45 addr = (addr + 1) % m; //开放定址法的 46 if (H.elem[addr + 1] == NULLKEY || addr == Hash(key))//如果循环回到原点 47 { 48 return UNSUCCESS; //关键字不存在 49 } 50 } 51 return SUCCESS; 52 } 53 54 55 int main() 56 { 57 int arr[HASHSIZE] = { 12,67,56,16,25,37,22,29,15,47,48,34 }; 58 int i, p, key, result; 59 HashTable H; 60 key = 39; 61 InitHashTable(H); 62 for (i = 0; i<m; i++) 63 InsertHash(H, arr[i]); 64 result = SearchHash(H, key, p); 65 if (result) 66 cout << "查找 " << key << " 的地址为: " << p << endl; 67 else 68 cout << "查找 " << key << " 失败。" << endl; 69 70 for (i = 0; i<m; i++) 71 { 72 key = arr[i]; 73 SearchHash(H, key, p); 74 cout << "查找 " << key << " 的地址为:" << p << endl; 75 } 76 return 0; 77 }
运行结果: