HashTable实现的错误结果

Wrong result in HashTable Implementation

本文关键字:结果 错误 实现 HashTable      更新时间:2023-10-16

我编写了下面的代码来实现HashTable链算法,但当我在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 :-/

谁能解释一下出了什么问题?

谢谢你的关注

你的问题是

void Insert (Link * head, HashEntry data)

改为

void Insert (Link *& head, HashEntry data)

基本上指针是通过值

传递的

你想做的事等于

void Bar( Link* input )
{   
   input = new Link();
}
Link* foo = 0;
Bar( foo );

Bar返回后foo 仍然是0。当按值传递指针时,可以修改指针所指向的内容,而不是指针本身。要使上述内容按预期工作,可以执行

备选项1

通过指针通过引用传递

void Bar( Link*& input )
{   
   input = new Link();
}
Link* foo = 0;
Bar( foo );

ALTERNATIVE 2

传递指针给指针

void Bar( Link** input )
{   
   *input = new Link();
}
Link* foo = 0;
Bar( &foo );

将指针头传递给按值插入函数,因此类哈希表中的数组"a"不会改变。通过引用传递解决了这个问题:

void Insert (Link *&head, HashEntry data)