HASH TABLE

#ifndef __HASEFUNTION_
#define __HASEFUNTION_

#include <string>
#include <ctime>
using std::string;

#define TABLE_SIZE 40

struct 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


HASH TABLE_第1张图片

 

 

HASH TABLE_第2张图片

你可能感兴趣的:(String,struct,table)