#include <iostream>
using namespace std;
typedef int ElementType;
struct ListNode
{
ElementType elem;
ListNode* next;
};
struct HashTable
{
int tableSize;
ListNode* *lists;
};
// 散列函数
unsigned int Hash(ElementType key, int tableSize)
{
return key % tableSize;
}
// 散列表——初始化
HashTable* InitializeTable(int tableSize)
{
HashTable* pHashTable;
// allocate table
pHashTable = (HashTable*)malloc(sizeof(struct HashTable));
if (pHashTable == NULL){
cout << "分配内存失败,Out of space!" << endl;
}
pHashTable->tableSize = tableSize; // NextPrime(tableSize);
// allocate array of lists
pHashTable->lists = (ListNode**)malloc(sizeof(struct ListNode));
if (pHashTable->lists == NULL){
cout << "分配内存失败,Out of space!" << endl;
}
// allocate list headers
for (int i = 0; i < pHashTable->tableSize; i++)
{
(pHashTable->lists)[i] = (ListNode*)malloc(sizeof(struct ListNode));
if ((pHashTable->lists)[i] == NULL){
cout << "分配内存失败,Out of space!" << endl;
}
else{
(pHashTable->lists)[i]->next = NULL;
}
}
return pHashTable;
}
// 散列表——查找
ListNode* Find(HashTable hashTable, ElementType elem)
{
int index = Hash(elem, hashTable.tableSize);// hash表(数组)中key(下标)
ListNode* list = hashTable.lists[index]; // 获取该index下的list
// 在list中寻找elem
while (list != NULL &&list->elem != elem)
{
list = list->next;
}
return list;
}
// 散列表——插入
void Insert(HashTable hashTabel, ElementType elem)
{
ListNode *node, *newCell;
// index为散列表中key
int index = Hash(elem, hashTabel.tableSize);
ListNode* list = Find(hashTabel, elem);
if (list == NULL) // 要插入的elem不存在
{
newCell = (ListNode*)malloc(sizeof(ListNode));
if (newCell != NULL)// 链表插入操作
{
node = hashTabel.lists[index];
newCell->next = node->next;
newCell->elem = elem;
node->next = newCell;
}
}
}
void main()
{
HashTable* hashTable = InitializeTable(10); //(HashTable*)malloc(sizeof(HashTable));
Insert(*hashTable, 0);
Insert(*hashTable, 1);
Insert(*hashTable, 4);
Insert(*hashTable, 9);
Insert(*hashTable, 16);
Insert(*hashTable, 25);
Insert(*hashTable, 36);
Insert(*hashTable, 49);
Insert(*hashTable, 64);
Insert(*hashTable, 81);
cout << Find(*hashTable, 0)->elem << endl;
cout << Find(*hashTable, 1)->elem << endl;
cout << Find(*hashTable, 4)->elem << endl;
cout << Find(*hashTable, 9)->elem << endl;
cout << Find(*hashTable, 16)->elem << endl;
cout << Find(*hashTable, 25)->elem << endl;
cout << Find(*hashTable, 36)->elem << endl;
cout << Find(*hashTable, 49)->elem << endl;
cout << Find(*hashTable, 64)->elem << endl;
cout << Find(*hashTable, 81)->elem << endl;
free(hashTable);
cin.get();
}
参考:《数据结构与算法分析》——C语言描述 冯舜玺 译