【问题标题】:C++ - Copying an Hash-table to another Hash-tableC++ - 将哈希表复制到另一个哈希表
【发布时间】:2013-01-10 01:50:01
【问题描述】:

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

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

这是我的代码:

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;
    }
}

}

【问题讨论】:

    标签: c++ pointers linked-list hashtable


    【解决方案1】:

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

    runner2 = table1[位置]; // runner2 变为 NULL
    runner2 = 新节点(临时); // runner2 现在包含指向 Node 的指针,但你的 table1[location] 仍然是 NULL。

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

    基本上你需要在整个 while(runner != NULL) 逻辑上工作。

    【讨论】:

      猜你喜欢
      • 2011-02-01
      • 2012-12-25
      • 2012-06-16
      • 1970-01-01
      • 2019-05-31
      • 1970-01-01
      • 2014-02-01
      • 2017-01-01
      • 2013-06-24
      相关资源
      最近更新 更多