处理哈希冲突方法之一:链地址法(将冲突的节点串起来)

本文详细探讨了处理哈希冲突的一种常见方法——链地址法,通过将发生冲突的节点链接在一起,实现对哈希表的有效管理。内容包括链地址法的基本原理、实现步骤及优缺点分析。
摘要由CSDN通过智能技术生成

先写头文件再写

#pragma once
typedef int ELEM_TYPE;
#define MAX_SIZE 12
//链地址法 中 后边连接的单链表的有效节点设计:
typedef struct Node 
{
	ELEM_TYPE data;//一个数据域
	struct Node *next;//一个指针域
}Node, *PNode;

//链地址法的 哈希表头设计
typedef struct Head
{
	struct Node arr[MAX_SIZE];  //数组  12个格子   每一个格子存放一个单链表的表头(用的是有效节点的结构体设计)
}Head, *PHead;
//函数
//初始化
void Init_list_hash(struct Head* hd);
//插入(头插)
bool Insert_head(struct Head *hd, ELEM_TYPE val);
//删除
bool Del_val(PHead hd, ELEM_TYPE val);
//查找
struct Node * Search(PHead hd, ELEM_TYPE val);
//判空
bool IsEmpty(PHead hd);
//获取有效个数
int Get_length(PHead hd);
//清空
void Clear(PHead hd);
//销毁
void Destroy(PHead hd);
//打印
void Show(PHead hd);

 再写cpp文件

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "list_hash.h"
//初始化//对那数组中的12个单链表头结点进行初始化
void In
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是使用地址处理哈希冲突的哈希查找的C语言实现代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 20 typedef struct node { int key; char *value; struct node *next; } Node; Node *hashTable[SIZE]; int hashFunction(int key) { return key % SIZE; } void insert(int key, char *value) { int index = hashFunction(key); Node *newNode = (Node *) malloc(sizeof(Node)); newNode->key = key; newNode->value = value; newNode->next = NULL; if (hashTable[index] == NULL) { hashTable[index] = newNode; } else { Node *temp = hashTable[index]; while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; } } char *search(int key) { int index = hashFunction(key); Node *temp = hashTable[index]; while (temp != NULL) { if (temp->key == key) { return temp->value; } temp = temp->next; } return NULL; } int main() { insert(1, "apple"); insert(2, "banana"); insert(3, "cat"); insert(4, "dog"); printf("%s\n", search(2)); // banana printf("%s\n", search(3)); // cat printf("%s\n", search(5)); // NULL return 0; } ``` 以上代码中,我们使用了一个大小为20的哈希表,并且实现了一个简单的哈希函数,即将键值对的键值取模。如果在插入时发现哈希表中对应位置为空,则直接插入该节点,否则在该位置的表末尾插入新节点。在查找时,首先通过哈希函数计算出对应位置,然后遍历该位置的表,寻找键值等于查找值的节点。如果找到了,则返回该节点的值,否则返回NULL。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值