哈希表,首先要确定表的大小。如果12个数据存到表大小为12的表中。则存的时候会比较浪费时间一些。
取值的时候一把就可以取出来。取得时候时间复杂度为O(1)
#ifndef HASH_H
#define HASH_H
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int DATATYPE;
typedef struct HASH_H
{
DATATYPE *head;
int tlen;
}Hash;
extern Hash *CreateHash(int len);
extern int DstroyHash(Hash *h);
extern int MyHash(Hash h,DATATYPEdata);
extern int HashInsert(Hash *h, DATATYPE data);
extern int HashSearch(Hashh,DATATYPE *data);
#endif // HASH_H
#include “hash.h”
Hash *CreateHash(int len)
{
Hash *temp = malloc(sizeof(Hash));
if(NULL == temp)
{
perror("CreateHash malloc");
return NULL;
}
temp->head = malloc(sizeof(DATATYPE)*len);
int i = 0;
for(i = 0; i<len; ++i)
{
temp->head[i] = -1;
}
temp->tlen = len;
return temp;
}
int DstroyHash(Hash *h)
{
free(h->head);
free(h);
return 0;
}
int MyHash(Hash h,DATATYPEdata)
{
return *data % h->tlen;
}
int HashInsert(Hash *h, DATATYPE *data)
{
int ind = MyHash(h,data);
while(h->head[ind]!= -1)
{
printf("insert---values %d, ind:%d\n",*data,ind);
ind = (ind+1) % h->tlen;
}
memcpy(&h->head[ind],data,sizeof(DATATYPE));
return ind;
}
int HashSearch(Hash*h,DATATYPE *data)
{
int ind = MyHash(h,data);
int temp = ind;
while(h->head[ind] != *data && h->head[ind]!=-1)
{
ind = (ind+1) % h->tlen;
printf("search---values %d, ind:%d\n",*data,ind);
if(temp == ind)
{
return -1;
}
}
return ind;
}
#include “hash.h”
int main(void)
{
int a[]={12,67,56,16,25,37,22,29,15,47,48,34};
//Hash* h = CreateHash(12);
Hash *h = CreateHash(12);
int i = 0 ;
DATATYPE data;
for(i =0; i< 12; ++i)
{
data = a[i];
HashInsert(h,&data);
}
data = 22;
int ind = HashSearch(h,&data);
if(ind < 0)
{
printf("not find val %d\n",data);
}
else
{
printf("find val is %d\n", data);
}
DstroyHash(h);
printf("Hello World!\n");
return 0;
}