因为Poj3349题目的原因,今天实现了数据结构里面的Hash表的算法。
采用的是分离链路法来处理冲突的,好像分离链路法运用的更加广泛一点。
思考了一下,觉得采用Hash的主要原因就是用空间换取时间吧,来快速的查询。
代码:
/**
*FILENAME: hash.c
*AUTHOR:XIANG CHANG SHENG
*CREATE ON:2013-1-31
*/
#include <stdio.h>
#include <stdlib.h>
/**
*DESCRIPTION:This file to implement the hash function.
We use separate chaining to solve the crash.
*/
struct HashNode {
int key;
struct HashNode *next;
};
struct HashTable {
int size;
struct HashNode **hash_list;
};
int hashKey(int size, int key) {
return key % size;
}
struct HashTable* createHashTable(int size) {
int i;
struct HashTable *hash_table = (struct HashTable *)malloc(sizeof(struct HashTable));
if (hash_table == NULL) {
printf("out of space");
return NULL;
}
hash_table->size = size;
hash_table->hash_list = (struct HashNode **)malloc(size * sizeof(struct HashNode *));
for (i = 0; i < hash_table->size; i++) {
hash_table->hash_list[i] = (struct HashNode *)malloc(sizeof(struct HashNode));
if(hash_table->hash_list[i] == NULL) {
printf("fatal error: out of memory");
return NULL;
}
hash_table->hash_list[i]->next = NULL;
}
return hash_table;
}
struct HashNode * hashFind(struct HashTable *hash_table, int key) {
int hash = hashKey(hash_table->size, key);
struct HashNode *hash_node;
for (hash_node = hash_table->hash_list[hash]->next; hash_node != NULL; hash_node = hash_node->next) {
if (hash_node->key == key) {
return hash_node;
}
}
return NULL;
}
void insert(struct HashTable *hash_table, int key) {
int hash = hashKey(hash_table->size, key);
if (hashFind(hash_table, key)) {
return ;
}
struct HashNode *hash_node= (struct HashNode *)malloc(sizeof(struct HashNode));
if (hash_node == NULL) {
printf("insert error,out of memory");
return ;
}
else {
hash_node->next = hash_table->hash_list[hash]->next;
hash_table->hash_list[hash]->next = hash_node;
hash_node->key = key;
}
}
void delete(struct HashTable *hash_table, int key) {
int hash = hashKey(hash_table->size, key);
struct HashNode *hash_node = hashFind(hash_table, key);
struct HashNode *temp;
if (hash_node == NULL) {
return ;
}
else {
for (hash_node = hash_table->hash_list[hash]; hash_node->next != NULL; hash_node = hash_node->next) {
if (hash_node->next->key == key) {
temp = hash_node->next;
hash_node->next = temp->next;
free(temp);
return ;
}
}
}
}
int main() {
struct HashTable *hash_table = createHashTable(101);
insert(hash_table, 100);
if (hashFind(hash_table, 100)) {
printf("success insert\n");
}
insert(hash_table, 201);
if (hashFind(hash_table, 201)) {
printf("success insert\n");
}
delete(hash_table, 100);
if (hashFind(hash_table, 100)) {
printf("delete wrong\n");
}
else {
printf("Yeah delete it\n");
}
delete(hash_table, 201);
if (hashFind(hash_table, 201)) {
printf("delete wrong\n");
}
else {
printf("Yeah delete it\n");
}
return 0;
}