HASH TABLE

来源:互联网 发布:接吻会传染什么病知乎 编辑:程序博客网 时间:2024/05/01 16:53
#ifndef __HASEFUNTION_#define __HASEFUNTION_#include <string>#include <ctime>using std::string;#define TABLE_SIZE 40struct HaseTable{string word;int co;};int Hase(const string &word){int cnt = 0;for (size_t i = 0; i < word.size(); ++i){cnt = cnt * 26 + word[i] - 'a';cnt &= (TABLE_SIZE - 1);}return ((cnt >> 8) ^ cnt) & (TABLE_SIZE - 1);}int RandProbe(int & cnt, HaseTable * hase){//冲突探测srand( 6 );for ( ; ; ){   cnt = (cnt + rand()) % TABLE_SIZE;   if (hase[cnt].co == 0)   return cnt;   else   hase[cnt].co++;}}int Find(HaseTable * hase,const string & word){int cnt = Hase(word);srand( 6 );while (hase[cnt].co != 0){if (strcmp(hase[cnt].word.c_str(), word.c_str()) == 0)return cnt;cnt = (cnt + rand()) % TABLE_SIZE;}return -1;}bool Add(HaseTable * hase, const string & word){if (Find(hase, word) != -1)return false;int cnt = Hase(word);if (hase[cnt].co != 0)cnt = RandProbe(cnt, hase);hase[cnt].co = 1;//strcpy(hase[cnt].word.c_str(), word.c_str());hase[cnt].word = word;return true;}bool Del(HaseTable * hase, const string & word){int cnt = Find(hase, word);if (cnt == -1)return false;hase[cnt].co = 0;return true;}#endif


 

 

原创粉丝点击