# include <stdio.h>
# include <string.h>
# include <windows.h>
# define MAX_SIZE 10
# define HASH_SIZE 10
typedef struct person{
char name[MAX_SIZE];
int age;
}Person;
typedef struct node{
Person * data;
struct node * next;
}Node;
typedef struct hashtable{
struct node * head;
int hash_size;
int count;
}HashTable;
int hashCode(Person * p){
int len = strlen(p->name);
int code = 0;
if(NULL == p->name)
code = 0;
else{
for(int i = 0; i < len; i++){
char ch = p->name[i];
code = (code << 5) - code + ch;
}
}
return code;
}
int Hash(Person * p){
return hashCode(p)% HASH_SIZE;
}
HashTable * CreateTable(){
HashTable * H = (HashTable *)malloc(sizeof(HashTable));
H->hash_size = HASH_SIZE;
H->count = 0;
H->head = (Node*)malloc(H->hash_size*(sizeof(Node)));
for(int i = 0; i < H->hash_size; i++)
H->head[i].next = NULL;
return H;
}
Node * Search(HashTable * H, Person * p){
int index = Hash(p);
Node * q = H->head[index].next;
while(q && strcmp(p->name, q->data->name))
q = q->next;
return q;
}
void Insert(HashTable * H, Person * p){
Node * q = Search(H, p);
if(q){
q->data->age = p->age;
strcpy(q->data->name, p->name);
}
else{
Node * New = (Node*)malloc(sizeof(Node));
New->data = (Person*)malloc(sizeof(Person));
New->data->age = p->age;
strcpy(New->data->name, p->name);
New->next = NULL;
int index = Hash(New->data);
if(NULL == H->head[index].next){
H->head[index].next = New;
}
else{
Node * r = H->head[index].next;
Node * s = r->next;
while(s){
r = s;
s = s->next;
}
r->next = New;
}
/*
New->next = H->head[index].next;
H->head[index].next = New;
*/
H->count++;
}
}
void Print(HashTable * H){
for(int i = 0; i < H->hash_size; i++){
Node * p = H->head[i].next;
if(!p)
printf("NULL");
while(p){
printf("%s--%d ", p->data->name, p->data->age);
p = p->next;
}
printf("\n");
}
printf("count = %d\n", H->count);
}
void Destory(HashTable ** H){
for(int i = 0; i < (*H)->hash_size; i++){
Node * p = (*H)->head[i].next;
while(p){
Node * q = p->next;
free(p);
p = q;
}
}
free((*H)->head);
(*H)->head = NULL;
free(*H);
*H = NULL;
}
int main(){
HashTable * H = CreateTable();
person p1 = {"jack", 18};
person p2 = {"Lily", 19};
person p3 = {"mike", 17};
person p4 = {"laven", 20};
person p5 = {"mike1", 22};
Insert(H, &p1);
Insert(H, &p2);
Insert(H, &p3);
Insert(H, &p4);
Insert(H, &p5);
Print(H);
Destory(&H);
Print(H);
system("pause");
return 0;
}