C++之简单哈希表查找法的实现和循环查找法的比较

散列表 (Hash table,也叫哈希表),是根据关键字(Key value)而直接访问在内存存储位置的数据结构。 也就是说,它通过计算一个关于键值的函数,将所需查询的数据映射到表中一个位置来访问记录,这加快了查找速度。 这个映射函数称做散列函数,存放记录的数组称做散列表

哈希表、二叉树、链表是最常见的数据结构,涵盖了程序员面试和笔试中几乎所有的数据结构相关问题。 本文中用C++来实现一个简单的哈希表,帮助理解哈希表是怎样运作的。为了简化代码并突出逻辑,采用简单的除余数作为 散列函数 ,用线性探测来 处理碰撞 。

#include 
#include 
#include 
using namespace std;

class HashItem{
	int key, val;
public:
	HashItem(int k, int v) : key(k), val(v){ };
	const int& getKey(){
		return key;
	}
	const int& getVal(){
		return val;
	}
};

#define LEN 25000*2
//#define LEN 8192

class HashTable{
public:
	static const int SIZE = LEN+2;//需要SIZE足够大,否则死循环
private:
	HashItem ** table;	  // 注意这是二级指针,指向对个HashItem*
public:
	HashTable(){
		table = new HashItem*[SIZE]();	 // 这里的括号是为了初始化为0
	}
	void set(int key, int val){
		int idx = key%SIZE;
		while (table[idx] && table[idx]->getKey() != key)
			idx = (idx + 1) % SIZE;		   // 当SIZE不够大时,这里会陷入死循环。可以检测一下。
		if (table[idx]) delete table[idx];
		table[idx] = new HashItem(key, val);
	}
	//采用简单的除余数作为散列函数,用线性探测来 处理碰撞。
	const int get(int key){
		int idx = key%SIZE;
		while (table[idx] && table[idx]->getKey() != key)
			idx = (idx + 1) % SIZE;           // SIZE不够大时,这里也面临死循环的问题
		return table[idx] ? table[idx]->getVal() : -1;      // 注意这里需要判断key不存在的情况
	}
	~HashTable(){
		for (int i = 0; i> n;
}

#include 
#include 
#include 
using namespace std;

class HashItem{
	int key, val;
public:
	HashItem(int k, int v) : key(k), val(v){ };
	const int& getKey(){
		return key;
	}
	const int& getVal(){
		return val;
	}
};

#define LEN 25000*2
//#define LEN 8192

class HashTable{
public:
	static const int SIZE = LEN+2;//需要SIZE足够大,否则死循环
private:
	HashItem ** table;	  // 注意这是二级指针,指向对个HashItem*
public:
	HashTable(){
		table = new HashItem*[SIZE]();	 // 这里的括号是为了初始化为0
	}
	void set(int key, int val){
		int idx = key%SIZE;
		while (table[idx] && table[idx]->getKey() != key)
			idx = (idx + 1) % SIZE;		   // 当SIZE不够大时,这里会陷入死循环。可以检测一下。
		if (table[idx]) delete table[idx];
		table[idx] = new HashItem(key, val);
	}
	//采用简单的除余数作为散列函数,用线性探测来 处理碰撞。
	const int get(int key){
		int idx = key%SIZE;
		while (table[idx] && table[idx]->getKey() != key)
			idx = (idx + 1) % SIZE;           // SIZE不够大时,这里也面临死循环的问题
		return table[idx] ? table[idx]->getVal() : -1;      // 注意这里需要判断key不存在的情况
	}
	~HashTable(){
		for (int i = 0; i> n;
}


你可能感兴趣的:(数据结构与算法,c/c++)