#define MAX_HASH_SIZE 10 // 按需调整
struct Node{
int data;
Node *next;
};
struct HashTable{
Node *head[MAX_HASH_SIZE];
};
void init_hash_table(HashTable &ht){
memset(&ht, 0, sizeof(ht)); // cstring头文件
}
void free_hash_table(HashTable &ht){
for(int i = 0; i < MAX_HASH_SIZE; i++){
Node *p = ht.head[i];
while(p != NULL){
Node *q = p;
p = p->next;
delete q;
}
}
}
bool find_data(HashTable &ht, int data){
int key = data % MAX_HASH_SIZE;
Node *p = ht.head[key];
while(p != NULL){
if(p->data == data){
return true;
}
p = p->next;
}
return false;
}
// 存在返回false,否则true
bool insert_data(HashTable &ht, int data){
if(find_data(ht, data)){
return false;
}
int key = data % MAX_HASH_SIZE;
Node *p = ht.head[key];
Node *q = new Node;
q->data = data;
q->next = p;
ht.head[key] = q;
return true;
}
// 不存在返回false,否则true
bool delete_data(HashTable &ht, int data){
int key = data % MAX_HASH_SIZE;
Node *p = ht.head[key];
if(p == NULL){
return false;
}
if(p->data == data){
Node *q = p;
ht.head[key] = p->next;
delete q;
return true;
}
Node *q = p;
p = p->next;
while(p && p->data != data){
q = p;
p = p->next;
}
if(p != NULL){
Node *u = p;
q->next = p->next;
delete u;
return true;
}
return false;
}