1、用散列表实现简单的英文词典
2011年4月4日星期一
一.头文件:
//文件名:Word.h
//单词类的定义
#include 2、word[25]; //用于存放单词
Word(){ for(int i=0; i<25; ++i) word[i]='\0';}
bool operator==(Word &r)//重载判断相等符号
{
if(strcmp(word,r.word)==0) return true;
else return false;
}
void operator=(Word &r) { strcpy(word,r.word); }//重载赋值运算符
};
//文件名:openHashTable.h
//开散列表
#incl 3、ude 4、y(const int &k) { return k; }//缺省值
int size;
public:
openHashTable(int length =101 , int(* f)(const Type &x) = defaultKey);
~openHashTable();
int find(Type &x); //查找函数
bool insert(Type &x); //插入函数
bool remove( Type &x); //删除函数
void output(); //输出词典函数
};
//================= 5、开散列表函数的实现=====================================
//构造函数的实现
template 6、 Type>
openHashTable 7、e &x)
{
int pos;
node *p;
pos = key(x)%size; //计算相对应的关键字
p = array[pos]->next;
while(p!=NULL && !(p->data==x)) p = p->next;
if(p==NULL)
{
p = new node(x);
p->next = array[pos]->next;
array[pos]->next = p;
return true;
}
return false;
}
//删除函数的实现
template 8、 9、/找到后删除
delete p;
return true;
}
}
//查找函数的实现
template 10、的桶位
else return 0; //没到找到就返回0
}
//打印词典函数的实现
template 11、i << "] ";
while(p!=NULL) //打印同一桶位,即有冲突的单词
{
cout << p->data;
if(p->next!=NULL) cout << " --> ";
if(p->next==NULL) cout << endl;
p = p->next;
}
}
}
}
二.Main函数的实现:
//文件名:openHashTableServesAs-A-DictionaryTest.cpp
//用散列表实现英文词典
#include "openHashTable 12、h"
#include "Word.h"
#include 13、的开散列表,即作为词典
while(!flag)
{
menu();
cin >> chioce;
switch(chioce)
{
case 'i': cout << " 请输入单词:";
cin.ignore(1,'\n');
cin.getline(w.word,25);
if(dictionary.insert(w)) cout << " 插入成功!" << endl;
else cout << " 这个单词已存在!" << endl;
break;
14、 case 'd': cout << " 请输入单词:";
cin.ignore(1,'\n');
cin.getline(w.word,25);
if(dictionary.remove(w)) cout << " 删除成功!" << endl;
else cout << " 这个单词不存在!" << endl;
break;
case 's': cout << " 请输入单词:";
cin.ignore(1,'\n');
cin.getline(w.word 15、25);
n = dictionary.find(w);
if(n!=0) cout << " 已找到,单词在第 " << n << " 桶中"<< endl;
else cout << " 这个单词不存在!" << endl;
break;
case 'v': cout << " 词典如下所示:" << endl;
dictionary.output();
break;
case 'q': flag = true;
break;
default: 16、 cout << " 输入错误!" << endl;
break;
}
}
}
//求权重函数的实现
int myHash(const Word &a)
{
unsigned long int num=0;
//从a(A)到z(Z)的权重依次为0到26
for(int i=0; a.word[i]!='\0'; ++i)//将单词的从左到右分别乘上的2排位次方,如第四位乘2的3次方
{
17、
if(a.word[i]>='a'&&a.word[i]<='z') num += (a.word[i] - '0'- 17 -32)*power(i);
else num += (a.word[i] - '0'-17)*power(i);
}
return num;
}
//求2的n次方函数的实现
int power(int n)
{
int num=1;
for(int i=1; i<=n; ++i) num *=2;
return num;
}
//打印菜单函数的实现
void menu()
{
cout << "\n==================== Menu =============================\n"
<< " i--insert d--delete s--search v--view q--exit \n"
<< " 请选择:";
}






