分离链接散列表的实现
做法:将散列到同一个值的所有元素保留到一个表中。
//分离链接散列表 separate chaining
//template<typename T>
struct ListNode;
//template<typename T>
typedef struct ListNode* Position;
typedef struct ListNode* List;
struct ListNode{
int element;
Position next;
};
struct HashTable{
int table_size;
List *the_lists;
};
//分离链接散列表 初始化例程
HashTable InitializeTable(int table_size){
HashTable *H;
H = new HashTable;
//H = malloc(sizeof(struct HashTable));
H->table_size = table_size;
H->the_lists = new List[table_size];
for (int i = 0; i != H->table_size; i++){
H->the_lists[i] = new ListNode();
//H->the_lists[i] = malloc(sizeof(struct ListNode));
H->the_lists[i]->next = NULL;
}
return *H;
}
//Insert 例程 可重复
void Insert(int key, HashTable H){
//Position pos, new_cell;
List list = H.the_lists[(key / H.table_size)];
ListNode* new_cell = new ListNode();
new_cell->element = key;
new_cell->next = list->next;
list->next = new_cell;
}
//Find例程
Position Find(int key, HashTable H){
List list = H.the_lists[(key / H.table_size)];
while (list != NULL && list->element != key){
list = list->next;
}
return list;
}
使用示例:
HashTable H = InitializeTable(7);
Insert(5, H);
Insert(7, H);
Position p=Find(5, H);
if (p != NULL){
cout << "find " << p->element << endl;
}
else{
cout << "not find" << endl;
}