//拉链法建立hash表
//hash.h
#ifndef Hash_H
#define Hash_H
#include <string>
using namespace std;
struct node{
node():next(NULL){}
string value;
node* next;
};
typedef node* HashNode;
const int MULT = 31;
const int TABLE_CAPACITY = 10000;
class Hash{
public:
Hash(HashNode* table);
~Hash();
void Insert(const string& word);
int Delete(const string& word);
int Search(const string& word);
private:
unsigned int hash(const string& word);//
HashNode* table;
};
#endif
//hash.cpp
#include "hash.h"
#include <iostream>
using namespace std;
Hash::Hash(HashNode* otherTable)
{
table=otherTable;
}
Hash::~Hash()
{
delete[] table;
}
unsigned int Hash::hash(const string& word)
{
const char* p=word.c_str();
unsigned int index = 0;
for (; *p; p++)
{
index = (index*MULT)%TABLE_CAPACITY+(*p)%TABLE_CAPACITY;
}
return index;
}
void Hash::Insert(const string& word)
{
int index = hash(word);
if (table[index] == NULL)
{
HashNode n =new node();
n->value=word;
n->next=NULL;
table[index]=n;
return ;
}
for (HashNode p=table[index];p;p = p->next)
{
if (p->value==word){
return ; //已经插入了
}
}
//发成冲突
HashNode n=new node();
n->value=word;
n->next=table[index];
table[index]=n;
}
int Hash::Delete(const string& word)
{
int index=hash(word);
if(!table[index]){
return -1;
}
else{
HashNode currentNode=table[index];
HashNode previousNode=currentNode;
if(currentNode->value==word){
table[index]=currentNode->next;
delete currentNode;
return 1;
}
else{
while(currentNode && currentNode->value!=word)
{
previousNode=currentNode;
currentNode=currentNode->next;
}
if(currentNode){
previousNode->next=currentNode->next;
delete currentNode;
return 1;
}
return -1;
}
}
}
int Hash::Search(const string& word)
{
int index=hash(word);
if (table[index]==NULL){
return -1;
}
for (HashNode p = table[index];p!=NULL;p=p->next)
{
if (p->value==word)
{
return 1;
}
}
return -1;
}
//main.cpp
/*
1.编写一个哈希(Hash)表类,以字符串作为作为关键字存放和查找记录,
提供公共成员函数进行哈希表的记录插入、查询和删除。
并在main函数中测试对该类的使用。
*/
#include "hash.h"
#include <iostream>
using namespace std;
int main(int argc,char** argv)
{
HashNode myTable[TABLE_CAPACITY] = {NULL};
Hash* ht = new Hash(myTable);
ht->Insert("IBM");
ht->Insert("联想");
ht->Insert("microsoft");
ht->Insert("慧谱");
ht->Insert("慧通");
ht->Insert("摩托罗拉");
cout<<"IBM"<< " : "<<ht->Search("IBM")<<endl;
cout<<"华为"<< " : "<<ht->Search("华为")<<endl;
cout<<"金山"<< " : "<<ht->Delete("金山")<<endl;
cout<<"联想"<< " : "<<ht->Delete("联想")<<endl;
return 0;
}