以下代码用开散列里的拉链法解决哈希冲突
#include <iostream>
#include <string.h>
using namespace std;
#define hashsize 3
struct movietype
{
char mname[20];
int time;
};
struct Node{
char* key;//一个关键值,存放的是指向char类型字符串的首地址
Node* next;//指针
};
class hashtable
{
private:
Node* node[hashsize];//hashsize需要自定义
public:
hashtable();//初始化哈希表
~hashtable();
unsigned int hasha(char * key);//返回值类型是unsigned int ,形参是一个字符串的首地址
Node* lookup(char * key);//查询函数
bool insert(char * key);//插入函数
void display();
};
hashtable::hashtable()
{
for(int i=0;i<hashsize;i++)
node[i]=NULL;
cout<<"建表成功!"<<endl;
}
hashtable::~hashtable(){}
unsigned int hashtable::hasha(char *key)
{
unsigned int h=0;
for(;*key;++key)
{
h=h*33 + *key;
}
//cout<<h % hashsize<<endl;
return h % hashsize;
}
Node* hashtable::lookup(char * key)
//查询函数,先计算出hasha的值,根据头结点去根据指针找结点,不成功则返回null,成功则返回这个结点的指针
{
Node * np;
unsigned int n;
n=hasha(key);
int a;
np=node[n];
while(np!=NULL)
{
if(! strcmp(key,np->key))//strcmp函数,相等返回0,小于(前面的字符串开头那个字母小于后面那个开头字母)返回负数,
{cout<<"success:头结点不为空,进入链表查找"<<"结点值为:"<<np->key<<endl;
return np;}//找到了
np=np->next;
}
//cout<<"没找到该节点!"<<endl;
return NULL;
}
bool hashtable::insert(char * key)
//插入函数,首先要查找是不是存在,存在的话返回false,不存在的话插入
{
Node* np;
unsigned int n;
if(np=lookup(key)) //找到了
{
cout<<"已经存在该节点!"<<endl;
return false;
}
else //未找到,插入,
{
n=hasha(key);
//np = (Node*)malloc(sizeof(Node));//分配一个Node
np=new Node;
np->key=key;//先把np的key和形参联系起来
if(node[n]==NULL)
{
node[n] = np;//头结点为空,直接把node[n]赋值为np
node[n]->next=NULL;//头结点下一个结点为空
}
else
{
np->next=node[n]->next;
node[n]->next=np;
//node[n]->next=np;
//np = node[n]->next;
//错误的两行
}
//cout<<"插入成功!"<<endl;
return true;
}
return true;
}
void hashtable::display(){
Node* temp;
for (int i = 0; i < hashsize; ++i)//循环node结点
{
if(!node[i]){
cout<<i<<"[]"<<endl;//空
}else{
temp=node[i];
while(temp!=NULL)
{
cout<<i;
cout<<"["<<temp->key<<"]";
temp=temp->next;
}
cout<<endl;
}
}
}
int main() {
int i;
hashtable *ht=new hashtable();
movietype waitingm;
movietype movie[]=
{
{"我和我的祖国",126},
{"我和我的家乡",145},
{"征途",106},
{"姜子牙",122}
};
for(i=0;i<4;i++)
{
char *arr =movie[i].mname;
ht->insert(arr);
}
ht->display();
cout<<"input:"<<endl;
char in[20];
cin>>in;
char* w;
w=in;
//char* w="征途";
ht->lookup(w);
if(ht->lookup(w))//找到结点,输出它的其他信息
{
for(i=0;i<4;i++)
if(!strcmp(movie[i].mname,w))
waitingm=movie[i];
cout<<waitingm.time;
}
return 0;
}