#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#define MAXSIZE 10
typedef int ElemType;
typedef struct HashNode
{
ElemType elem;
struct HashNode* next;
}HashNode;
typedef struct
{
HashNode* Hashtable[MAXSIZE];
}Hash;
HashNode* BuyNode()
{
HashNode* s = (HashNode*)malloc(sizeof(HashNode));
if (nullptr == s) exit(1);
memset(s, 0, sizeof(HashNode));
return s;
}
void FreeNode(HashNode* p)
{
free(p);
}
void Init_Hash(Hash* phash)
{
assert(phash != nullptr);
for (int i = 0; i < MAXSIZE; ++i)
{
phash->Hashtable[i] = BuyNode();
}
}
bool Insert_Elem(Hash* phash, ElemType val)
{
assert(phash != nullptr);
int pos = val % MAXSIZE;
HashNode* newnode = BuyNode();
newnode->next = phash->Hashtable[pos]->next;
phash->Hashtable[pos]->next = newnode;
newnode->elem = val;
return true;
}
bool Search(Hash* phash, ElemType val)
{
assert(phash != nullptr);
for (int i = 0; i < MAXSIZE; ++i)
{
HashNode* p = phash->Hashtable[i]->next;
while (p != nullptr)
{
if (p->elem == val)
{
return true;
}
p = p->next;
}
}
return false;
}
HashNode* Search_Pre(Hash* phash, ElemType val)
{
assert(phash != nullptr);
for (int i = 0; i < MAXSIZE; ++i)
{
HashNode* p = phash->Hashtable[i];
while (p->next != nullptr)
{
if (p->next->elem == val)
{
return p;
}
p = p->next;
}
}
return nullptr;
}
bool Delete_Elem(Hash* phash, ElemType val)
{
assert(phash != nullptr);
HashNode* p = Search_Pre(phash, val);
HashNode* q = p->next;
p->next = q->next;
FreeNode(q);
q = nullptr;
return true;
}
void Clear_Hash(Hash* phash)
{
assert(phash != nullptr);
for (int i = 0; i < MAXSIZE; ++i)
{
HashNode* p = phash->Hashtable[i];
while (p->next != nullptr)
{
HashNode* q = p->next;
p->next = q->next;
FreeNode(q);
q = nullptr;
}
}
}
void Destory_Hash(Hash* phash)
{
assert(phash != nullptr);
Clear_Hash(phash);
for (int i = 0; i < MAXSIZE; ++i)
{
FreeNode(phash->Hashtable[i]);
phash->Hashtable[i] = nullptr;
}
}
void Print_HashTable(Hash* phash)
{
assert(phash != nullptr);
for (int i = 0; i < MAXSIZE; ++i)
{
if (phash->Hashtable[i] == nullptr) exit(1);
HashNode* p = phash->Hashtable[i]->next;
printf("%d :", i);
while (p != nullptr)
{
printf("%d ", p->elem);
p = p->next;
}
printf("\n");
}
printf("\n");
}
先是按插入的元素打印,然后再删除一个元素,然后再清空哈希表,最后销毁哈希表