博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hash算法与拉链法解决冲突
阅读量:4613 次
发布时间:2019-06-09

本文共 1372 字,大约阅读时间需要 4 分钟。

key = $key; $this->value = $value; $this->nextNode = $nextNode; }}class HashTable{ private $buckets; private $size = 10; public function __construct() { $this->buckets = []; } private function hashfunc($key) { $strlen = strlen($key); $hashval = 0; for ($i = 0; $i < $strlen; $i++) { $hashval += ord($key[$i]); } return $hashval % $this->size; } public function insert($key, $value) { $index = $this->hashfunc($key); //新创建一个节点 if (isset($this->buckets[$index])) { $newNode = new HashNode($key, $value, $this->buckets[$index]); } else { $newNode = new HashNode($key, $value, NULL); } $this->buckets[$index] = $newNode; //保存新节点 } public function find($key) { $index = $this->hashfunc($key); $current = $this->buckets[$index]; while (isset($current)) { if($current->key == $key){ return $current->value; } var_dump($current);die; $current = $current->nextNode; } return NULL; }}

解释:

1.使用Hash函数计算关键字的Hash值,通过Hash值定位到Hash表的指定位置

2.如果此位置已经被其他节点占用,把新节点的$nextNode指向此节点,否则把新节点的$nextNode设置为NULL

3.把新节点保存到Hash表的当前位置

4.遍历当前链表,比较链表中每个节点的关键字与查找关键字是否相等

转载于:https://www.cnblogs.com/kerwing/p/9154865.html

你可能感兴趣的文章
你还在为使用P/Invoke时,写不出win32 api对应的C#声明而犯愁吗?
查看>>
Codeforces Educational Codeforces Round 3 B. The Best Gift 水题
查看>>
Docker安装Gitlab
查看>>
C++虚函数和纯虚函数的区别
查看>>
vue.js:搭建开发环境及构建项目
查看>>
【设计模式】学习笔记14:状态模式(State)
查看>>
原生JQ实现图片滑动轮播
查看>>
composer
查看>>
CentOS配置smtp发邮件
查看>>
我的博客
查看>>
JSTL函数
查看>>
tensorflow中tensor与数组之间的转换
查看>>
有限状态机
查看>>
【转】 c#中两个DateTimePicker,一个时间设置为0:0:0,另一个设置为23:59:59
查看>>
history对象 screen对象
查看>>
composer 实现自动加载原理
查看>>
Windows环境npm无法生效
查看>>
软Raid50制作
查看>>
第一次作业-随笔
查看>>
Python 实现图片上表格的写入
查看>>