【发布时间】:2011-12-28 14:40:41
【问题描述】:
我编写了下面的代码来实现HashTable by Chains算法,但是当我在main函数中使用它时,结果是错误的:
#define _SIZE 1000
class HashEntry
{
public: int Tel;
string Name;
public: HashEntry(){}
public: HashEntry(int Tel, string Name)
{
this->Tel = Tel;
this->Name = Name;
}
};
class Link {
public:
HashEntry data;
Link *next;
public:
Link() : next(NULL){ }
};
void Insert (Link *head, HashEntry data)
{
Link *t= new Link;
t->data=data;
if(head==NULL)
{
head = new Link;
head->next = NULL;
head->data = data;
return;
}
Link *head2= head;
while(head2->next!=NULL)
{
if( head2->data.Name == data.Name)
return;
head2=head2->next;
}
head2->next=t;
}
class HashTable {
public:
Link **a;
public:
HashTable()
{
a = new Link *[_SIZE];
for (int i=0; i<_SIZE; i++)
a[i]=NULL;
}
public:
int HashFonction (string key)
{
int res=0;
for ( int i = 0; i < key.length(); i ++ )
{
char ch = key.at(i);
if( i%2==0)
res+=(int)ch;
else
res-=(int)ch;
}
return (int)fabsf((float)res) % _SIZE;
}
void HashInsert (string key, int val){
int index= HashFonction(key);
HashEntry s(val, key);
Insert(a[index],s);
}
int HashSearch(string key)
{
int inx=HashFonction(key);
Link *head=a[inx];
if(head==NULL){
return -1;
}
while(head!=NULL){
if(head->data.Name==key)
return head->data.Tel;
head=head->next;
}
return -1;
}
};
实现这个类后,我编写了以下代码,但搜索的结果是-1:-/
HashTable ht;
ht.HashInsert("Hossein", 849348);
ht.HashInsert("Ali", 94343);
ht.HashInsert("Fatemeh", 940343);
cout << ht.HashSearch("Ali") << endl; // output = -1 :-/
任何人都可以解释什么是错的吗?
感谢您的关注
【问题讨论】:
-
你应该调试你的代码并尝试找出它到底是哪里失败了。在插入阶段? [如果是 - 在哪里?] 在搜索中? [为什么搜索失败?]
-
我觉得还挺对的!我不知道它到底在哪里失败:-/
-
你应该使用调试器[或者如果你的 IDE 没有调试器,则使用一堆 printf] 并首先检查所有插入是否正确完成......如果没有 - 尝试调查 正是它失败了,然后继续寻找,并以同样的方式检查它。
-
我觉得Link类有问题!你能找到吗? :-/
标签: c++ data-structures hashtable