Day 59 哈希表储存

哈希表,首先要确定表的大小。如果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(Hash
h,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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值