#ifndef _HASH_
#define _HASH_
#define N 15
typedef int datatype;
typedef struct node{
datatype key;
datatype value;
struct node *next;
}listnode,*linklist;
typedef struct {
listnode data[N];
}hash;
hash * hash_create();
int hash_insert(hash *HT,datatype key);
linklist hash_search(hash * HT,datatype key);
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.h"
hash * hash_create(){//哈希表创建
hash *ht;
ht=(hash *)malloc(sizeof(hash));
if(ht==NULL)
return NULL;
memset(ht,0,sizeof(hash));
return ht;
}
int hash_insert(hash *HT,datatype key){
if(HT==NULL) return -1;
linklist p,q;
p=(linklist)malloc(sizeof(listnode));
if(p==NULL){
printf("malloc failed\r\n");
return -1;
}
p->key=key;
p->value=key%N;
p->next=NULL;
//找到插入位置
q=&(HT->data[p->value]);
//在哪个数据后面插入
while(q->next&&q->next->key < p->key){
q=q->next;
}
//插入
p->next=q->next;
q->next=p;
return 0;
}
linklist hash_search(hash * HT,datatype key){//查找
if(HT==NULL) return NULL;
linklist p;
p=&(HT->data[key%N]);
while(p->next&&p->next->key!=key){
p=p->next;
}
if(p->next==NULL){
printf("not found1\r\n");
return NULL;
}else{
printf("found2\r\n");
return p;
}
}