哈希表拉链法问题
#include <stdio.h>
#include <stdlib.h>
#define MAX 13
typedef int datatype;
typedef struct node
{
datatype key;
struct node *next;
}hashnode;
void creat_hash(int a[], int n, int m, hashnode *hash[])
{
int i;
int j;
hashnode *p;
/*for(i=0; i<m; i++)
hash[i].next = NULL;*/
for(i=0; i<n; i++)
{
p = (hashnode *)malloc(sizeof(hashnode));
p->key = a[i];
j = a[i]%m;
p->next = hash[j];这里
hash[j] = p;还有这里##################################################################
}
}
void show(hashnode *hash[], int n ,int m)
{
int i;
hashnode *p;
printf("hash is:\n");
for(i=0; i<m; i++)
{
printf("%2d", i);
p = hash[i];
while(p != NULL)
{
printf("%4d", p->key);
p = p->next;
}
printf("\n");
}
}
hashnode *hash_search(hashnode *hash[], int k, int m)
{
hashnode *p;
int d = k%m;
p = hash[d];
while(p && p->key != k)
p = p->next;
return p;
}
int main(void)
{
int k;
hashnode *p;
int a[] = {23,34,14,38,46,16,68,15,07,31,26};
int n = 11;
int m = MAX;
hashnode *hash[MAX] = {NULL};
creat_hash(a, n, m, hash);
show(hash, n ,m);
printf("input the number for search:");
scanf("%d", &k);
p = hash_search(hash,k,m);
if(p == NULL)
printf("the number is not exist\n");
else
printf("is :%d\n", p->key);
return 0;
}
程序中标注的地方不应该是 p->next = hash[j]->next;
hash[j]->next = p;问了百度,没人回答,希望高手们帮帮忙
[解决办法]
程序中标注的地方不应该是 p->next = hash[j]->next;
hash[j]->next = p
这是尾插入法
在插入第一个的节点的时候hash[j]为NULL,不能得到next指针的
你给的代码没有问题,使用了头插入