我正在尝试通过将当前哈希表的元素复制到另一个哈希表来“重新调整大小”哈希表,更改第一个哈希表的大小并将元素复制回来。顺便说一下,当从第一个到第二个复制时,使用第二个哈希表的大小重新计算元素的位置。
我的问题是第二个哈希表甚至没有打印第二个哈希表。
这是我的代码:
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;
}
}
}
答案 0 :(得分:1)
快速浏览一下。其中一个错误是:
runner2 = table1 [location]; // runner2变为NULL
runner2 = new Node(temp);
// runner2现在包含指向Node的指针,但是table1 [location]仍然是NULL。
另外你链接列表逻辑是错误的。您的节点没有连接。 你应该做的事情如下: runner-&gt; next = new Node(temp);
基本上你需要在整个(run!= NULL)逻辑上工作。