#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
int **elem;
int count;
int sizeindex;
}HashTable;
#define SUCCESS 1
#define UNSUCCESS 0
#define DUPLICATE -1
#define MOD_VALUE 11
#define TABLE_LEN 11
void IniteHashTable(HashTable *H)
{
H->elem = (int **)malloc(TABLE_LEN * sizeof(int *));
for (int index = 0; index < TABLE_LEN; ++index)
{
H->elem[index] = NULL;
}
H->count = 0;
H->sizeindex = TABLE_LEN;
}
int Hash(int key)
{
return key % MOD_VALUE;
}
int Collision(int position, int d)
{
return (position + d) % MOD_VALUE;
}
int SearchHash(HashTable H, int key, int *position, int *count)
{
*position = Hash(key);
while ((H.elem[*position] != NULL) && (*(H.elem[*position]) != key))
{
++(*count);
*position = Collision(*position, *count);
}
if (H.elem[*position] == NULL)
{
return UNSUCCESS;
}
else
{
return SUCCESS;
}
}
int InsertHash(HashTable *H, int e)
{
int count = 0;
int position = 0;
if (SearchHash(*H, e, &position, &count))
{
return DUPLICATE;
}
else if(count < H->sizeindex / 2)
{
H->elem[position] = (int *)malloc(sizeof(int));
*(H->elem[position]) = e;
++H->count;
return SUCCESS;
}
else
{
return UNSUCCESS;
}
}
HashTable* CreateHashTable()
{
HashTable *H = (HashTable *)malloc(sizeof(HashTable));
IniteHashTable(H);
printf("录入一组关键字序列,以\";\"分割\n");
char buffer[TABLE_LEN*2];
scanf("%s", buffer);
char *token;
token = strtok(buffer, ";\t\n");
while (token != NULL)
{
int liv_tmp = atoi(token);
InsertHash(H, liv_tmp);
token = strtok(NULL, ";\t\n");
}
return H;
}
void PrintHashTable(HashTable *H)
{
for (int index = 0; index < H->sizeindex; ++index)
{
if (H->elem[index] == NULL)
{
printf(" *,");
}
else
{
printf(" %d,", *(H->elem[index]));
}
}
}
void main()
{
HashTable *MyHashTable;
MyHashTable = CreateHashTable();
PrintHashTable(MyHashTable);
printf("\n");
printf("输入要查找的关键字:");
int key;
scanf("%d", &key);
int position = 0;
int count = 0;
int flag = SearchHash(*MyHashTable, key, &position, &count);
if (flag == SUCCESS)
{
printf("关键字存在\n");
printf("此关键字位置:%d\n", position + 1);
}
else
{
printf("关键字不存在\n");
}
}