记录个demo吧。
建立hash表和search一定要用同一的hash算法。
#include <stdio.h>
#include <stdlib.h>
#define Max 6
#define HashMax 5
int data[Max] = {12, 160, 219, 522, 725, 9997};
int HashTable[HashMax] = {0};
int counter = 1;
struct LinkList
{
int key;
struct LinkList *next;
};
typedef struct LinkList Node;
typedef Node *Link;
Node HashTable_linklist[HashMax] = {0};
static int hash_mod(int key)
{
return key%HashMax;
}
static int collision_offset(int addr)
{
int offset = 3;
return (addr + offset)%HashMax;
}
static int create_hash_linklist(int key)
{
Link pointer;
Link new_node;
int index;
new_node = (Link) malloc(sizeof(Node));
new_node->key = key;
new_node->next = NULL;
index = hash_mod(key);
pointer = HashTable_linklist[index].next;
if (pointer != NULL)
{
new_node->next = pointer;
HashTable_linklist[index].next = new_node;
}
else
HashTable_linklist[index].next = new_node;
return 0;
}
int hash_search_linklist(int key)
{
Link pointer;
int index;
counter = 0;
index = hash_mod(key);
pointer = HashTable_linklist[index].next;
printf("Data[%d]: ", index);
while(pointer != NULL)
{
counter++;
printf("[%d]", pointer->key);
if (pointer->key == key)
return 1;
else
pointer = pointer->next;
}
return 0;
}
static int create_hash(int key)
{
int hash_time = 0;
int collision_time = 0;
int address = hash_mod(key);
int i;
while (hash_time < HashMax)
{
if (HashTable[address] == 0) /*尚未被占用*/
{
HashTable[address] = key;
printf("Key : %d => Address %d\n", key, address);
for(i = 0; i < HashMax; i++)
{
printf("[%d]", HashTable[i]);
}
printf("\n");
return 1;
}
else
{
collision_time++;
printf("Collision %d => Address %d\n", collision_time, address);
address = collision_offset(address);
}
hash_time++;
}
return 0;
}
/*建立hash Table 必须和Search用同样的方式*/
static int hash_search(int key)
{
int address;
counter = 0;
address = hash_mod(key);
while(counter < HashMax)
{
counter++;
if (HashTable[address] == key)
return 1;
else
address = collision_offset(address);
}
return 0;
}
int main(int argc, char **argv)
{
int key = 522;
int index = 0;
int i = 0;
while(index < Max)
{
if (create_hash(data[index]))
printf("Hash Success\n");
else
printf("Hash Fulled\n");
index++;
}
printf("Hash Table : \n");
for (i = 0; i < HashMax; i++)
{
printf("[%d]", HashTable[i]);
}
printf("\n");
if (hash_search(key))
printf("Search Time = %d\n", counter);
else
printf("Didnot find %d\n", key);
counter = 0;
index = 0;
while(index < Max)
{
if (create_hash_linklist(data[index]))
printf("Hash Success\n");
else
printf("Hash Fulled\n");
index++;
}
Link pointer;
printf("Linklist Hash Table : \n");
for (i = 0; i < HashMax; i++)
{
printf("Table %d: ", i);
pointer = HashTable_linklist[i].next;
while(pointer != NULL)
{
if (pointer->key > 0)
printf("[%d]", pointer->key);
pointer = pointer->next;
}
printf("\n");
}
printf("\n");
printf("goint to search linklist\n");
if (hash_search_linklist(key))
printf("\nLinkList Search Time = %d\n", counter);
else
printf("Didnot find %d\n", key);
}