哈希(hash) 之 开放地址法(poj)

本文介绍了哈希表中的开放地址法,特别是线性探测再散列,讨论了其工作原理和优缺点。通过C++代码展示了如何插入和搜索元素,并提供了一个完整的程序实例。程序读取输入数据,使用开放地址法处理哈希表,并输出最终结果。
摘要由CSDN通过智能技术生成
#include <iostream>
#include<stdio.h>
using namespace std;
const int size=20345677;
const int M=1000000000;
const int key=1357;
typedef struct Hash
{
    int val;
    int cp;
}Hash;
Hash hash[size];
// 线性探测再散列,为啥全部加M呢,因为 n 可能为-2 的28次方
void insert(int n)
{哈希表(散列表)开放寻址法:包括 线性探查(如本文);二次探查(加平方);双重散列。
把关键字从非自然数转化为自然数N,字符串的一般用ELFHash()更搞笑;
开放地址法在删除方面不如链接法(链表法),他不能够随意的删掉一个元素而不做任何处理,否则查找同一个映射的元素将失败
开放地址法是将所有的元素都放在散列表中,装载因子绝对不会超过1.
 int t=n;
 n=(n+M)%size;
 while(hash[n].val!=M&&hash[n].val!=t)
 {
  n=(n+key)%size;
 }
 hash[n].val=t;
 hash[n].cp++;
}
int search(int n)
{
 int t=n;
 n=(n+M)%size;
 while(hash[n].val!=M&&hash[n].val!=t)
 {
  n=(n+key)%size;
 }
 if(hash[n].val==M) return 0;
 else return hash[n].cp;
}


int main()
{
 int 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现代码及其原理如下: 原理: 哈希表开放地址法,是一种处理哈希碰撞(哈希冲突)的方。刚开始时,哈希表中全部元素都未被占用,当要将一个新元素添加到哈希表中时,通过哈希函数计算其所对应的哈希地址,如果该地址已经被占用,就继续往下查找,直到找到一个空的地址为止。 实现代码: #include <stdio.h> #include <stdlib.h> #include <string.h> #define HASHSIZE 12 // 定义哈希表数组长度为12 #define NULLKEY -32768 // 定义空关键字,同时也可以做删除标记 typedef struct { int key; // 关键字 } DataNode; // 数据节点类型 DataNode HashTable[HASHSIZE]; // 定义哈希表数组 // 初始化哈希表 void InitHashTable() { for (int i = 0; i < HASHSIZE; ++i) { HashTable[i].key = NULLKEY; // 将哈希表中全部元素的关键字值初始化为NULLKEY } } // 散列函数 int Hash(int key) { return key % HASHSIZE; // 除留余数 } // 插入元素 void InsertElement(int key) { int hashVal = Hash(key); // 计算key的哈希地址 while (HashTable[hashVal].key != NULLKEY) // 如果该地址已被占用 { // 线性探测,继续往下查找 hashVal = (hashVal + 1) % HASHSIZE; } HashTable[hashVal].key = key; // 将新元素插入哈希表 } // 查找元素 void SearchElement(int key) { int hashVal = Hash(key); // 计算key的哈希地址 while (HashTable[hashVal].key != key) // 未找到时继续查找 { if (HashTable[hashVal].key == NULLKEY) { printf("该关键字不存在!\n"); // 哈希表中没有该元素,退出查找 return; } // 线性探测,继续往下查找 hashVal = (hashVal + 1) % HASHSIZE; } printf("该元素的位置是:%d\n", hashVal); // 找到该元素,输出其在哈希表中的位置 } // 删除元素 void DeleteElement(int key) { int hashVal = Hash(key); // 计算key的哈希地址 while (HashTable[hashVal].key != key) // 未找到时继续查找 { if (HashTable[hashVal].key == NULLKEY) { printf("该关键字不存在!\n"); // 哈希表中没有该元素,退出删除 return; } // 线性探测,继续往下查找 hashVal = (hashVal + 1) % HASHSIZE; } HashTable[hashVal].key = NULLKEY; // 将该元素标记为NULLKEY,即删除该元素 } int main() { InitHashTable(); // 初始化哈希表 InsertElement(56); // 插入元素 InsertElement(22); InsertElement(37); InsertElement(15); InsertElement(23); InsertElement(24); printf("输入要查找的数据:"); int key; scanf("%d", &key); SearchElement(key); // 查找元素 printf("输入要删除的数据:"); scanf("%d", &key); DeleteElement(key); // 删除元素 return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值