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