#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define HASHSIZE 12
#define NULLKEY -(1<<31)
int m;
typedef struct
{
int *elem;
int count;
}HashTable;
void Init(HashTable *H)
{
m = HASHSIZE;
H->count = 0;
H->elem = (int *)malloc(m*sizeof(HashTable));
for(int i = 0; i < m; i++)
H->elem[i] = NULLKEY;
}
int Hash(int key)
{
return key % m;
}
bool InsertHash(HashTable *H,int key)
{
if(H->count == m)
return false;
int addr = Hash(key);
while(H->elem[addr] != NULLKEY)
{
if(H->elem[addr] == key)
return false;
addr = (addr+1) % m;
}
H->elem[addr] = key;
H->count++;
return true;
}
bool SearchHash(HashTable *H,int key)
{
int addr = Hash(key);
while(H->elem[addr] != key)
{
addr = (addr+1)%m;
if(addr == Hash(key) || H->elem[addr] == NULLKEY)
return false;
}
printf("%d\n",addr);
return true;
}
int main()
{
int a[13] = {12,67,56,16,25,37,22,29,15,47,48,34,12};
HashTable H;
Init(&H);
for(int i = 0; i < 13; i++)
{
if(InsertHash(&H,a[i]))
printf("%d insert succeed!\n",a[i]);
else
printf("%d:In or fulled.Failed!\n",a[i]);
}
for(int i = 0; i < 13; i++)
{
printf("%d key:",a[i]);
SearchHash(&H,a[i]);
}
return 0;
}
|