分别写出在散列表中插入和删除关键字为K的一个记录的算法,设散列函数为H,解决冲突的方法为链地址法。

cs 复制代码
#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;
}
相关推荐
小O的算法实验室1 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法
小飞学编程...1 小时前
【哈希表】
数据结构·哈希算法·散列表
Tbisnic2 小时前
BGE-M3 算法详解:从模型架构到三种检索方式的数学原理
算法·自然语言处理·大模型·bert·transformer·注意力机制
Brilliantwxx2 小时前
【算法从零到千】【55-58】哈希位图+常见数学运算 接口
算法
空堂与归3 小时前
用户分群找不到规律?用K-Means聚类算法自动发现数据模式
算法·机器学习·kmeans·聚类
动词ing4 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习4 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
一只小小的芙厨5 小时前
基础数论总结
笔记·学习·算法
动词ing5 小时前
【C语言】结构体+文件基础
c语言·开发语言·数据结构
caimouse5 小时前
ReactOS 窗口系统分析(7):分层窗口与绘制辅助 — layered.c + draw.c
c语言·开发语言