【发布时间】:2019-11-26 07:07:54
【问题描述】:
它没有编译,它在新节点的声明处停止。 程序本身应该初始化一个哈希表并打印冲突以及哈希表内部有多少。 它似乎内存不足,但我只插入了 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;
}
【问题讨论】:
-
首先不要强制转换malloc:stackoverflow.com/q/605845/6872717
-
询问编译错误时,包括实际的编译错误听起来很有用。
-
使用
malloc(sizeof(*ptr));而不是malloc(sizeof(type));,这是面向未来的。 -
如果您将第一句更改为“它不起作用,它在分配新节点时停止。”那么这个问题就更有意义了。
-
@Justanotherstudent:真的有编译错误吗?还是像 Ian Abbott 假设的那样是一个错字?您能否通过编辑问题来澄清实际发生的情况(充分详细地描述所需的行为和实际行为)?