字符串hash实现

124 阅读1分钟
#include<iostream>
#include<string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

//实现hash表

class Node {
public:
	string data;
	Node* next = nullptr;
};

class Hash {
private:
	int MOD = 1000;
	int BASE = 233;
public:
	Node* data[1000] = { nullptr };
	Hash();
	~Hash();//注意析构内存管理
	int get_hash(string& s);
	bool compare(string& s, string& t);
	void add(string& s);
	void add(const char* cs);
	bool find(string& s);
	bool find(const char* cs);
	void erase(string& s);
	void erase(const char* cs);
};

Hash::Hash() {
	for (int i = 0; i < 1000; i++) {
		data[i] = new Node;
		data[i]->next = new Node;
	}
}

Hash::~Hash() {
	for (int i = 0; i < 1000; i++) {
		while (data[i]!=nullptr){
			Node* temp = data[i];
			data[i] = data[i]->next;
			delete temp;
		}
	}
}

int Hash::get_hash(string& s) {
	int res = 0;
	for (size_t i = 0; i < s.size(); i++) {
		res = (res * BASE + s[i]) % MOD;
	}
	return res;
}

bool Hash::compare(string& s, string& t) {
	return get_hash(s) == get_hash(t);
}

void Hash::add(string& s) {
	int res = get_hash(s);
	Node* cur = this->data[res];

	while (cur->next != nullptr) {
		cur = cur->next;
	}

	Node* newNode = new Node;
	cur->next = newNode;
	cur->data = s;
}
void Hash::add(const char* cs) {
	string s = cs;
	add(s);
}
bool Hash::find(string& s) {
	int res = get_hash(s);
	Node* cur = this->data[res];
	while (cur->next != nullptr) {
		if (cur->data == s) {
			return true;
		}
		cur = cur->next;
	}
	return false;
}
bool Hash::find(const char* cs) {
	string s = cs;
	return find(s);
}
void Hash::erase(string& s) {
	int res = get_hash(s);
	Node* before = this->data[res];

	while (before->next != nullptr) {
		if (before->next->data == s) {
			Node* cur = before->next;

			if (cur->next != nullptr) {
				Node* next = cur->next;
				delete cur;
				before->next = next;
				continue;
			}
			else {
				delete cur;
				before->next = nullptr;
				continue;
			}
		}
		before = before->next;
	}
}
void Hash::erase(const char* cs) {
	string s = cs;
	return erase(s);
}

int main() {
	Hash hash;
	hash.add("1235");
	hash.add("3456");
	cout << hash.find("3456");
	hash.erase("3456");
	cout << hash.find("3456");

}