標頭檔案 hashtable.h
複製** **如下:
typedef struct _bucket
bucket;
typedef struct _hashtable
hashtable;
int hash_init(hashtable **ht);
int hash_find(hashtable *ht, char *key, void **result);
int hash_insert(hashtable *ht, char *key, void *value);
int hash_remove(hashtable *ht, char *key);
int hash_loop(hashtable *ht, void **result);
//int hash_index(hashtable *ht, char *key);
static unsigned int elfhash(char *str, unsigned int length);
hashtable.c
複製** **如下:
#include
#include
#include
#include "hashtable.h"
#include "mempool.h"
#include "log.h"
#define success 1
#define failed 0
#define hash_len 5
int hash_init(hashtable **ht)
(*ht)->size = 0;
(*ht)->total = hash_len;
bucket *bucket = (bucket *)malloc(sizeof(bucket) * hash_len);
memset(bu 0, sizeof(sizeof(bucket) * hash_len));
(*ht)->buckets = bucket;
return success;
}int hash_insert(hashtable *ht, char *key, void *value)
int index = hash_index(ht, key);
bucket *bucket = &ht->buckets[index];
int _tmpindex;
char _tmpindexstr[20];
while (null != bucket->value)
bucket = bucket->next;
}do while (_tmpindex == index || ht->buckets[_tmpindex].value != null);
index = _tmpindex;
bucket->next = &ht->buckets[index];
bucket = bucket->next;
}bucket->key = (char *)malloc(sizeof(key));
bucket->value = (void *)malloc(sizeof(value));
memcpy(bucket->key, key, sizeof(key));
memcpy(bucket->value, value, sizeof(value));
bucket->next = null;
ht->size ++;
return success;
}int hash_find(hashtable *ht, char *key, void **result)
while (strcmp(key, bucket->key)) else
}if (null == bucket->value || strcmp(key, bucket->key))
*result = bucket->value;
return success;
}int hash_delete(hashtable *ht, char *key)
&nbsqrihxzap; while (strcmp(key, bucket->key)) else
}if (null == bucket->value || strcmp(key, bucket->key))
memset(bucket, 0, sizeof(bucket));
ht->size --;
return success;
}void hash_status(hashtable *ht)
int hash_index(hashtable *ht, char *key)
// elf hash function
static unsigned int elfhash(char *str, unsigned int length)
}//返回乙個符號位為0的數,即丟棄最高位,以免函式外產生影響。(我們可以考慮,如果只有字元,符號位不可能為負)
return (hash & 0x7fffffff) % length;
}其中key的對映使用的是 elfhash 演算法
本文標題: c語言實現的hashtable分享
本文位址:
C語言實現乙個簡易的Hash table 二
上一章,簡單介紹了hash table,並提出了本教程中要實現的幾個hash table的方法,有search a,k insert a,k,v 和delete a,k 本章將介紹hash table使用的資料結構。hash表中儲存的每一項key value的資料結構 hash table.h ty...
C語言實現乙個簡易的Hash table 三
上一章,我們講了hash表的資料結構,並簡單實現了hash表的初始化與刪除操作,這一章我們會講解hash函式和實現演算法,並手動實現乙個hash函式。本教程中我們實現的hash函式將會實現如下操作 我們將會設計乙個普通的字串hash函式,在偽 中表示如下 function hash string,a...
C語言實現乙個簡易的Hash table 六
上一章中,我們實現了hash表中的插入 搜尋和刪除介面,我們在初始化hash表時固定了大小為53,為了方便擴充套件,本章將介紹如何修改hash表的大小。現在,我們的hash表是固定大小 53 的,當插入越來越多資料時,我們的hash表就會被插滿,這個問題有兩個原因 雜湊表的效能隨著高衝突率而降低 我...