用链地址法处理冲突,构建哈希表:假设哈希表长为m,哈希函数为H(x),用链地址法处理冲
#include<stdio.h>
#include<stdlib.h>
#define SIZE 12
typedef struct _HashNode
{
int data ;
struct _HashNode *next;
}HashNode;
typedef struct _HashList
{
HashNode * elem[SIZE];
int size;
}HashList;
int Hash(int size,int key)
{
return key%size;
}
HashNode *InsertHash(HashNode *head,int key)
{
if(head == NULL)
{
printf("head == NULL\n");
HashNode *p = (HashNode *)malloc(sizeof(struct _HashNode));
p->data = key;
p->next = NULL;
return p;
}
HashNode *ph = head;
while(ph != NULL)
{
if(ph->data == key)
{
return head;
}
if(ph->next == NULL)
{
HashNode *p = (HashNode *) malloc(sizeof(struct _HashNode));
p->data = key;
p->next = NULL;
ph->next = p;
return head;
}
else ph = ph->next;
}
}
int main()
{
int a[12] = {19,14,23,1,68,20,84,27,55,11,10,79};
printf("ok\n");
HashList hashlist;
hashlist.size = SIZE;
int i;
for(i = 0;i<hashlist.size;i++)
{
hashlist.elem[i] = NULL;
}
for(i=0;i<12;i++)
{
int sit = Hash(hashlist.size,a[i]);
printf("sit = %d, a[%d] = %d\n",sit,i,a[i]);
hashlist.elem[sit] = InsertHash(hashlist.elem[sit],a[i]);
}
printf("---------------------------\n");
for(i = 0;i<12;i++)
{
printf("%d: ",i+1);
HashNode *p = hashlist.elem[i];
while(p!=NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
}