文档详情

C++英文词典的简单实现.doc

发布:2017-05-10约4.91千字共7页下载文档
文本预览下载声明
用散列表实现简单的英文词典 2011年4月4日星期一 一.头文件: //文件名:Word.h //单词类的定义 #include cstring #include iostream.h class Word{ friend ostream operator(ostream os, const Word obj)//重载输出函数 { int n=strlen(obj.word); for(int i=0; in; ++i) os obj.word[i]; return os; } public: char word[25]; //用于存放单词 Word(){ for(int i=0; i25; ++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 //开散列表 #include cstring #include iostream.h template class Type class openHashTable{ private: struct node{//私有结点 Type data; struct node *next; node(){ next = NULL; } node(Type d){ data = d; next = NULL;} }; node **array; int(*key)(const Type x);//关键字 static int defaultKey(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(); //输出词典函数 }; //======================开散列表函数的实现===================================== //构造函数的实现 template class Type openHashTableType::openHashTable(int length, int(*f)(const Type x)) { size = length; array = new node *[size]; key = f; for(int i=0; isize; ++i) array[i] = new node; } //析构函数的实现 template class Type openHashTableType::~openHashTable() { node *p, *q; for(int i=0; isize; ++i) { p = array[i];//分别析构每一个桶的相应链 do{ q = p-next; delete p; p = q; }while(p!=NULL); } delete [] array; } //插入函数的实现 template class Type bool openHashTableType::insert(Type 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 class Type bool openHashTableType::remove(Type x) { int pos; node *p, *q; pos = key(x)%size; //
显示全部
相似文档