【数据结构】哈希表类的C++实现

大概就是给一堆数据,根据数据的值决定它的储存位置,比如新建一个大小为20的数组,把元素10放在10的位置,15放在15的位置,元素和位置的关系由哈希函数决定,这里用的是除留取余函数。

using namespace std;
#define HASHSIZE 12
#define NULLKEY  -327168

class HashTable
{
private:
	int* elem;//元素指针数组
	int count;//元素个数
public:
	HashTable() { elem = NULL;count = 0; }
	int init();
	int Hash(int key);
	void insert(int key);
	int search(const int &key);
};

int HashTable::init()
{
	count = HASHSIZE;
	elem = new int[HASHSIZE];
	if (elem == NULL)
	{
		cout << "error in makespace\n";
		return -1;
	}
	for (int i = 0;i < HASHSIZE;i++)
	{
		elem[i] = NULLKEY;
	}
	return 0;
}

int HashTable::Hash(int key)
{
	return key % HASHSIZE;//除留余数法
}

void HashTable::insert(int key)
{
	int addr;
	addr = Hash(key);
	while (elem[addr] != NULLKEY)
	{
		addr = Hash(addr + 1);
	}
	elem[addr] = key;
}

int HashTable::search(const int &key)
{
	int addr = NULLKEY;
	addr = Hash(key);
	while (elem[addr] != key)
	{
		addr = Hash(addr + 1);
		if (elem[addr] == NULLKEY || addr == Hash(key))//该地址元素为空或者回到起点
		{
			cout << "no element\n";
			return addr;
		}

	}
	return addr;
}

int main()
{
	HashTable table;
	table.init();
	for (int i = 0;i <HASHSIZE;i++)
	{
		int key = i*3+5;
		table.insert(key);
		cout << key << " ";
	}
	cout << endl;
	
	int add=table.search(10);
	if (add == HASHSIZE)
	{
		cout << "no found" << endl;
	}
	return 0;
}

输入的值是 5 8 11 14 17 20 23 26 29 32 35 38
哈希表中的值是 23, 35, 14, 26, 38, 5, 17, 29, 8, 20, 32, 11
找元素10 并没有找到
找元素20 输出位置 9

你可能感兴趣的:(数据结构)