1 //散列表 2 #include<iostream> 3 using namespace std; 4 #define NULLKEY -32768 5 #define HASHSIZE 12 //定义散列表长度为12 6 7 struct HashTable 8 { 9 int *elem; //数据元素存储基址 10 int count; //当前数组元素个数 11 }; 12 13 int m = 0; //散列表长度 14 15 //初始化散列表 16 bool InitHashTable(HashTable *H) 17 { 18 m = HASHSIZE; 19 H->count = m; 20 H->elem = new int[m]; 21 for(int i=0;i<m;i++) 22 H->elem[i] = NULLKEY; 23 return true; 24 } 25 26 //散列函数 27 int Hash(int key) 28 { 29 return key % m; 30 } 31 32 //插入关键字进散列表 33 void InsertHash(HashTable *H, int key) 34 { 35 int addr = Hash(key); 36 while(H->elem[addr] != NULLKEY) 37 { 38 addr = (addr+1)%m; 39 } 40 H->elem[addr] = key; 41 } 42 43 //散列表查找关键字 44 bool SearchHash(HashTable H, int key, int *addr) 45 { 46 *addr = Hash(key); 47 while(H.elem[*addr] != key) 48 { 49 *addr = (*addr+1)%m; 50 if(H.elem[*addr]==NULLKEY || *addr == Hash(key)) 51 return false; 52 } 53 return true; 54 } 55 56 int main() 57 { 58 int arr[HASHSIZE]={12,67,56,16,25,37,22,29,15,47,48,34}; 59 int i,p,key,result; 60 HashTable H; 61 62 key=39; 63 64 InitHashTable(&H); 65 for(i=0;i<m;i++) 66 InsertHash(&H,arr[i]); 67 68 result=SearchHash(H,key,&p); 69 if (result) 70 cout<<"查找 "<< key <<" 的地址为:"<<p<<endl; 71 else 72 cout<<"查找 "<< key <<" 失败。"<<endl; 73 74 for(i=0;i<m;i++) 75 { 76 key=arr[i]; 77 SearchHash(H,key,&p); 78 cout<<"查找 "<< key <<" 的地址为:"<<p<<endl; 79 } 80 81 return 0; 82 }
原文:http://www.cnblogs.com/jx-yangbo/p/5958077.html