#include<stdbool.h>
//定义链表结构
typedef struct LNode
{int data;struct LNode* next;
}LNode,*LinkList;
//假设散列表的大小为100
#define TABLE_SIZE 100
LinkList HT[TABLE_SIZE];//散列函数
int hash(int data)
{return data % TABLE_SIZE;//所有data都会存储在0-TABLE_SIZE-1的位置里面
}void initialize_hash_table()
{//给每个链表申请空间for (int i = 0; i < TABLE_SIZE; i++){HT[i] = (LinkList)malloc(sizeof(LNode));if (HT[i] == NULL){perror("error");exit(1);}HT[i]->next = NULL;}
}//插入
bool insert(int data)
{int ant = hash(data);//拿到哈希地址LinkList p = HT[ant];//p指向这个哈希地址while (p->next)//判断HT[ant]后的data有没有跟当前的相等{if (p->next->data == data){return false;}p = p->next;}//没相等的data就插入新节点LinkList s = (LinkList)malloc(sizeof(LNode));if (s == NULL){perror("error:");return false;}s->data = data;s->next = p->next;p->next = s;return true;
}//删除函数
bool delete_key(int data)
{int ant = hash(data);LinkList p = HT[ant];while (p->next){if (p->next->data == data){LinkList s = p->next;p->next = s->next;free(s);return true;}p = p->next;}return false;
}
int main()
{//初始化链表initialize_hash_table();insert(1);insert(10);insert(20);insert(30);insert(10);//插入失败的for (int i = 0; i < 100; i++) {LinkList p = HT[i]->next;if (p != NULL) {printf("Slot %d: %d\n", i, p->data);}}printf("\n");delete_key(10);delete_key(1);for (int i = 0; i < TABLE_SIZE; i++) {LinkList p = HT[i]->next;if (p != NULL) {printf("Slot %d: %d\n", i, p->data);}}for (int i = 0; i < TABLE_SIZE; i++){free(HT[i]);}return 0;
}