2

我试图通过将当前哈希表的元素复制到另一个哈希表来“重新调整”哈希表的大小,更改第一个哈希表的大小并将元素复制回来。顺便说一句,当从第一个复制到第二个时,使用第二个哈希表的大小重新计算元素的位置。

我的问题是第二个哈希表甚至没有打印第二个哈希表。

这是我的代码:

void intHashTable::rehash(int size){

new_table = true;

cout<< "REHASH "<< endl;
//table1 is the second/temporary hash-table
//with the size of the new hash-table
table1 = new Node*[size];
//counter is reset
number_of_elements = 0;
int temp;
//Runner is used to traverse table1
Node * runner2;

//set the nodes to null
for ( int i = 0; i < size; i++ ) {
    table1[i] = NULL;
}
//
for ( int i = 0; i < prev_size; i++ ) {
    Node * runner = table[i];
    while(runner != NULL){
        temp = runner->num;
        cout<<"temp: "<<runner->num<<"\n";
        //get new location
        int location = ((unsigned)temp) % size;
        cout<<"location: "<<location<<"\n";
        //store in new location
        runner2 = table1[location];
        runner2 = new Node(temp);
        cout<<runner2->num<<"\n";
        runner = runner->next;
        runner2 = runner2->next;
    }
}

//print out second/temporary hash-table
for(int i =0; i < size; i++){
    Node *runner  = table1[i];
    cout<< i << ". ";
    while(runner != NULL){
        cout<< runner->num << " ";
        runner = runner->next;
    }
    cout<<endl;
}
//re-sizing original table
table = new Node*[size];
cout<< "New size " <<size<<endl;

for ( int i = 0; i < size; i++ ) {
    table[i] = NULL;
}
//copying the second/temp back to the first/original
for ( int i = 0; i < size; i++ ) {
   Node * runner = table1[i];
    while(runner != NULL){
        temp = runner->num;
        Node * runner2 = table[i];
        runner2 = new Node(temp);
        cout<<runner2->num<<"\n";
        runner = runner->next;
        runner2 = runner2->next;
    }
}

}

4

1 回答 1

1

快速浏览了一下。错误之一是:

runner2 = table1 [位置];// runner2 变为 NULL
runner2 = new Node(temp); // runner2 现在包含指向节点的指针,但您的 table1[location] 仍然为 NULL。

你的链接列表逻辑也是错误的。您的节点未连接。您应该执行以下操作: runner->next = new Node(temp);

本质上,您需要在整个 while(runner != NULL) 逻辑上工作。

于 2013-01-26T02:15:42.613 回答