出力結果がこのように、初期に定義した-1の値が出る時と出ない時があります。なぜなのでしょうか?線形リストができていないのでしょうか?よろしくお願いします。
0 120 0x7ff974c059f0 0x7ff974c05a00
910 0x7ff974c05a00 0x0
1 -1 0x7ff974c05940 0x7ff974c05a10
411 0x7ff974c05a10 0x0
2 -1 0x7ff974c05950 0x0
3 -1 0x7ff974c05960 0x0
4 344 0x7ff974c059d0 0x7ff974c05a20
824 0x7ff974c05a20 0x0
5 -1 0x7ff974c05980 0x7ff974c05a40
435 0x7ff974c05a40 0x0
6 676 0x7ff974c059e0 0x7ff974c05a50
426 0x7ff974c05a50 0x0
7 -1 0x7ff974c059a0 0x0
8 -1 0x7ff974c059b0 0x7ff974c05a30
658 0x7ff974c05a30 0x0
9 -1 0x7ff974c059c0 0x7ff974c05a60
529 0x7ff974c05a60 0x0
C++
1#include <iostream> 2#include <cstdlib> 3using namespace std; 4#define HASH_NUM 10 //ハッシュデーブルの要素数m 5#define N 10 //入力データ数n 6 7struct CELL{ 8 int data; 9 CELL *next; 10}; 11 12int Hash(int); 13void add_hash_struct(CELL**,int); 14void show_hash_struct(CELL**); 15 16 17int main() 18{ 19 CELL *HashTable[HASH_NUM]; 20 21 for(int i = 0; i < HASH_NUM; i++){ 22 HashTable[i] = new CELL; 23 HashTable[i]->data = -1; 24 HashTable[i]->next = NULL; 25 } 26 27 srand((unsigned int)time(NULL)); 28 int x; 29 for(int i = 0; i < N; i++){ 30 x = rand() % 900 + 100; 31 add_hash_struct(HashTable,x); 32 x = 0; 33 } 34 35 show_hash_struct(HashTable); 36 37} 38 39int Hash(int x) 40{ 41 return x % HASH_NUM; 42} 43 44void add_hash_struct(CELL **HT,int x) 45{ 46 CELL *newcell = new CELL; 47 48 int key; 49 key = Hash(x); 50 51 while(HT[key]->next != NULL){ 52 HT[key] = HT[key]->next; 53 } 54 55 newcell->next = NULL; 56 HT[key]->next = newcell; 57 newcell->data = x; 58} 59 60void show_hash_struct(CELL **HT) 61{ 62 CELL *p = new CELL; 63 for(int i = 0; i < HASH_NUM; i++){ 64 cout << i << " " ; 65 while(HT[i] != NULL){ 66 cout << HT[i]->data << " " << HT[i] << " " << HT[i]->next << endl; 67 HT[i] = HT[i]->next; 68 } 69 cout << endl; 70 } 71}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/07/04 13:01
2021/07/04 13:05
2021/07/04 13:16
2021/07/04 13:41
2021/07/04 14:25