您的位置:首页 > 其它

Hash表基本操作

2015-07-12 10:43 337 查看
#include<stdio.h>
#include<stdlib.h>

#define HASHSIZE 12
#define NULLKEY -32768

typedef struct _Hash
{
int *elmt;
int count;
}_Hash;
typedef struct _Hash HashTable;
int m = 0;

void InitHash(HashTable* H)
{
int i;
m = HASHSIZE;
H->elmt  = (int*)malloc(sizeof(int)*m);
H->count = 0;
for(i = 0;i < m; i++)
{
H->elmt[i] = NULLKEY;
}
}

int Hash_(int key)
{
return key%m;
}

void InsertKey(HashTable* H,int key)
{
int pos = Hash_(key);
int i = 0;
while((H->elmt[pos])!= NULLKEY)
{
i++;
pos = (pos+i)%HASHSIZE;
if(pos == Hash_(key))
{
printf("已经没有空位置给元素:%d\n",key);
return ;
}
}
(H->count)++;
printf("第 %d 次插入:元素 %d 冲突 %d 次,插入位置:%d\n",H->count,key,i,pos);
H->elmt[pos] = key;
}
int Search(HashTable H,int key)
{
int pos = Hash_(key);

while(H.elmt[pos] != key)//冲突
{
pos = (pos + 1)%HASHSIZE;
if(H.elmt[pos] == NULLKEY || pos == Hash_(key))
{
printf("没有找到元素%d\n",key);
return -1;
}
}
return pos;
}
int main()
{
int arr[HASHSIZE+1] = {2,3,7,4,6,8,1,5,9,18,10,-1,20};
int i,pos = 0;
HashTable H;
InitHash(&H);
for(i = 0 ;i < HASHSIZE+1 ;i++)
{
InsertKey(&H,arr[i]);
}
for(i = 0 ;i < HASHSIZE+1 ;i++)
{
pos = Search(H,arr[i]);
if(pos != -1)
printf("元素:%d ,在位置:%d\n",arr[i],pos);
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: