我一直在尝试完全实现我的散列表,但我并不完全理解代码是如何工作的。我的头文件设置正常,我只是缺少实现以下内容:
V * find(K key)
- 我想返回指向我正在寻找的值的指针,或者显然为null。
bool addOrMod(K key, V val)
- 添加一个新元素,如果添加了值,则返回状态(true或false)。
int size()
- 它只返回我的词典中有多少项。
我还认为我没有在int hash(string s)
感谢您的帮助。
这是我的班级:
#include "Dic.h"
#include <string>
int Dic::hash(K key){ //DEPENDS ON K. This one assumes K is string
return -1; //stub code
}
void Dic::deallocate(){ //separate member called by destruc and op=
for(int i=0; i<SZ; i++){
//get rid of chain i
DicNode * p = table[i];
while(p!=0){
DicNode * kill = p;
p = p->nxt;
delete kill;
}
}
delete [] table;
}
V * find(K) {
return *location;
}
bool addOrMod(K, V){
return added;
}
int size(){
return size;
}
//-----------------------------------------------------------------
//BIG 3
Dic::Dic() {
}
int hash(string s) {
int ret=0;
int SZ = s.length();
for (int i=0; i<s.size(); i++) {
ret+=s[i]-'A';
}
return ret%SZ;
}
Dic::~Dic(){this->deallocate();}
Dic::Dic( const Dic & src ){ //copy con
*this = src; //Uses operator= defined for Dic
}
Dic & Dic::operator=( const Dic & rhs ){ //assignment op
if(this == &rhs){ cout<<"goofy"<<endl; return *this; }
// clean up any memory allocated by this
this->deallocate();
// initialize this n,SZ,table to be like rhs
this->n=rhs.n; this->SZ = rhs.SZ; this->table=new DicNode*[SZ];
// duplicate the DicNode chains
for(int i=0;i<SZ;i++){
DicNode * q = rhs.table[i];
if(q==0){
this->table[i]=0;
}else{
this->table[i]=new DicNode; //note: NOT DicNode()
DicNode * p = this->table[i];
while(true){ //loop inv: *p is blank node corresp to *q
p->key = q->key; p->val = q->val;
if(q->nxt==0)break;
q=q->nxt; p->nxt=new DicNode; p=p->nxt;
}
p->nxt=0;
}
}
return *this;
}