2

現在のハッシュテーブルの要素を別のハッシュテーブルにコピーし、最初のハッシュテーブルのサイズを変更して、要素を元にコピーすることにより、ハッシュテーブルの「サイズを変更」しようとしています。ちなみに、1枚目から2枚目にコピーする場合、要素の位置は2枚目のハッシュテーブルのサイズで再計算されます。

私の問題は、2 番目のハッシュ テーブルが 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

ざっと見てみました。エラーの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 に答える