分别写出在散列表中插入和删除关键字为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;
}
相关推荐
灰灰勇闯IT1 分钟前
ops-reduce:ReduceMax 与 ReduceMean 的并行优化
算法
水木流年追梦10 分钟前
大模型入门-Reward 奖励模型训练
开发语言·python·算法·leetcode·正则表达式
JavaWeb学起来10 分钟前
Python学习教程(六)数据结构List(列表)
数据结构·python·python基础·python教程
沙威玛_LHE19 分钟前
P13376题解
算法
枕星而眠32 分钟前
Linux 四大进程/线程同步锁详解:互斥锁、读写锁、条件变量、文件锁
linux·c语言·后端·ubuntu·学习方法
DFT计算杂谈41 分钟前
KPROJ编译教程
java·前端·python·算法·conda
重生之我是Java开发战士1 小时前
【笔试强训】Week5:空调遥控, kotor和气球,走迷宫,主持人调度II,体操队形,二叉树的最大路径和,排序子序列,消减整数
java·算法·动态规划
社交怪人1 小时前
【数字对调】信息学奥赛一本通C语言解法(题号2070)
c语言·开发语言
hef2881 小时前
C语言中char指针与数组的区别及应用
c语言·开发语言
吃好睡好便好2 小时前
用if…end…语句计算分段函数
开发语言·人工智能·学习·算法·matlab