#include<stdio.h>
#include<stdlib.h>
#include<memory.h>
/****************采用链接法的双向哈希链表*********************/
#define maxnum 10
typedef struct node
{
struct node* next;
struct node* prev;
int data;
}Node,*pNode;
typedef struct hash
{
pNode table[maxnum];
}Hash,*pHash;
pHash initHash()
{
pHash p = (pHash)malloc(sizeof(Hash));
memset(p,0,sizeof(Hash));
return p;
}
//散列函数
int hashfunc(int num)
{
return (num%maxnum);
}
pNode finddata(pHash hash,int data)
{
int key = hashfunc(data);
pNode tmp = hash->table[key];
while(tmp && tmp->data != data)
{
tmp = tmp->next;
}
if(tmp)
return tmp;
else
return NULL;
}
//这里数据在头部加入,而非整个节点,node结构在里面动态分配
int insertHash(pHash hash,int data)
{
int key;
if(hash == NULL)
printf("Hash table has not been created\n");
else
{
key = hashfunc(data);
if(hash->table[key] == NULL)//散列指对应的链表为空,最简单情况
{
pNode tmp = (pNode)malloc(sizeof(Node));
memset(tmp,0,sizeof(Node));
tmp->data = data;
hash->table[key] = tmp;
tmp->prev = NULL;
tmp->next = NULL;
return 0;
}
else if(finddata(hash,data) != NULL)
{
printf("data already exist cant insert %d !\n",data);
return -1;
}
else
{
pNode tmp = (pNode)malloc(sizeof(Node));
memset(tmp,0,sizeof(Node));
tmp->data = data;
tmp->next = hash->table[key];
hash->table[key]->prev = tmp;
hash->table[key] = tmp;
tmp->prev = NULL;
return 0;
}
}
}
int deletHash(pHash hash,int data)
{
int key = hashfunc(data);
pNode tmp = finddata(hash,data);
if(tmp)
{
if(tmp->prev == NULL)//删除的是头结点
{
if(tmp->next)
{
tmp->next->prev = NULL;
hash->table[key] = tmp->next;
}
else //只有一个节点情况
hash->table[key] = NULL;
}
else if(tmp->next == NULL)
tmp->prev->next = NULL;
else
{
tmp->next->prev = tmp->prev;
tmp->prev->next = tmp->next;
}
free(tmp);
return 0;
}
else
{
printf("data does not exist cant delet %d !\n",data);
return -1;
}
}
void printHash(pHash hash)
{
int key=0;
pNode tmp = NULL;
printf("-------Hash table is :-------\n");
for(key=0;key<maxnum;key++)
{
tmp= hash->table[key];
printf("table[%d]-->",key);
while(tmp)
{
printf("%2d->",tmp->data);
tmp = tmp->next;
}
printf(" null\n");
}
}
void destroyHash(pHash hash)
{
int key;
pNode tmp,pre;
for(key=0;key<maxnum;key++)
{
tmp = hash->table[key];
while(tmp)
{
pre = tmp;
tmp = tmp->next;
free(pre);
}
}
printf("Destroy hash table complete!\n");
}
int main(void)
{
pHash hash = initHash();
insertHash(hash,1);
insertHash(hash,2);
insertHash(hash,3);
insertHash(hash,4);
insertHash(hash,11);
insertHash(hash,12);
insertHash(hash,13);
insertHash(hash,15);
insertHash(hash,22);
insertHash(hash,129);
insertHash(hash,0);
printHash(hash); //第一次打印
deletHash(hash,1);
deletHash(hash,12);
deletHash(hash,4);
deletHash(hash,4); //删除已经删除的元素
insertHash(hash,13); //添加已经存在的元素
printHash(hash); //第二次打印
destroyHash(hash);
return 0;
}
自己实现的hash表,散列函数就写了这一种,后续还会有进一步补充,希望跟进一步了解hash表,毕竟这个BAT面试笔试都会有哦,加油!!代码如有错误欢迎指正。