它不编译并且在新节点的声明处停止。 程序本身应该初始化一个哈希表并打印冲突以及哈希表中有多少冲突。 它似乎内存不足,但我只插入了 5 个元素,所以它不应该这样做。 也许它是结构之间的错误?我无法得到它。
typedef struct item{
int key;
struct item *next;
}item;
typedef struct hash{
item *head;
int count;
} hash;
int hashing(int x , int a , int b , int table_size){
int p = 999149;
return ((a*x + b) % p) % 2*table_size;
}
item * insert_list( int x){
item *new;
new = (item*)malloc(sizeof(item));
new->key = x;
new->next = NULL;
return new;
}
void insert( hash* ht, int x , int a , int b , int table_size){
int index = hashing( x , a ,b , table_size);
item *new_node=insert_list(x);
if(!ht[index].head){
ht[index].head = new_node;
ht[index].count++;
return;
}
new_node->next = (ht[index].head);
ht[index].head = new_node;
ht[index].count++;
return;
}
int main(){
int n, a , b, i , x;
scanf("%d", &n);
scanf("%d", &a);
scanf("%d" , &b);
int *longest = malloc(sizeof(int)*2);
hash *T = (hash*) malloc (n*sizeof(hash));
for( i = 0 ; i < 2*n ; i++) {
T[i].head= NULL;
T[i].count= 0;
}
for ( i = 0 ; i < n ; i++){
scanf("%d" , &x);
insert( T, x , a , b ,2*n);
}
int max_l=-1;
int counter=0;;
for( i = 0 ; i < 2*n ; i++) {
if (max_l< T[i].count)max_l = T[i].count;
if(T[i].count >1 ) counter= counter + T[i].count;
}
printf("%d\n%d", max_l, counter);
return 0;
}
最佳答案
hash *T = (hash*) malloc (n*sizeof(hash));
for( i = 0 ; i < 2*n ; i++) {
T[i].head= NULL;
T[i].count= 0;
}
您为 n
个元素分配内存,但循环到 2*n
,您需要什么?
关于c - malloc 错误,我无法理解使用具有单独链接的哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57076013/