使用拉链法解决冲突的简单hash表
2016-09-29 00:00
330 查看
摘要: 使用拉链法解决冲突的简单hash表
Hash函数的作用是把任意长度的输入,通过hash算法变换成固定长度的输出,该输出就是hash值,hash表的复杂度为O(1)。
Hash函数的作用是把任意长度的输入,通过hash算法变换成固定长度的输出,该输出就是hash值,hash表的复杂度为O(1)。
<?php /** * 一个简单的hash表 * 使用拉链法解决冲突 */ class hashtable{ private $buckets; //存储数据数组 private $size = 10; public function __construct(){ $this -> buckets = new SplFixedArray($this->size); } /** * 通过把字符串相加取余得到hash值 * @param string $key 关键字 * @return int hash值 */ private function hashfunc($key){ $strlen = strlen($key); $hashval = 0; for ($i=0; $i < $strlen; $i++) { $hashval += ord($key[$i]); } return $hashval%$this->size; } /** * 1. 使用hsahfuc计算关键字的hash值,通过hash值定位到hash表的指定位置 * 2. 如果此位置已经被占用,把新节点的$NextNode指向此节点,否则把$NextNode设置为NULL * 3. 把新节点保存到hash表中 * @param string $key 关键字 * @param string $value 值 * @return void */ 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; } $current = $current->nextNode; } } } class HashNode{ public $key; //节点关键字 public $value; //节点的值 public $nextNode; //具有相同hash值的节点的指针 public function __construct($key,$value,$nextNode=null){ $this -> key = $key; $this -> value = $value; $this -> nextNode = $nextNode; } } $test = new hashtable(); $test -> insert('key1','value1'); $test -> insert('key12','value12'); $test -> insert('key2','value2'); var_dump($test -> find('key1')); var_dump($test -> find('key12')); var_dump($test -> find('key2')); ?>
相关文章推荐
- HASH表解决冲突———双链表循环使用
- HASH表解决冲突———双链表循环使用…
- 使用swiper轮播图手写js之后冲突简单解决办法
- 简单描述ListView中使用GestureDetector冲突的解决办法
- Git基本使用方法简介及简单的解决冲突的方法
- 使用dbms_rectifier_diff解决高级复制中的数据冲突问题
- subversion冲突解决和winmerge使用手册
- 解决IP地址冲突的方法--DHCP SNOOPING 经实验,使用效果非常好
- 让TortoiseSVN使用类似TortoiseCVS的文件冲突解决方式
- subversion冲突解决和winmerge使用手册
- XP和Win7双系统GhostXP或重装XP后无法使用Win7的简单解决办法
- 一步一步SharePoint 2007之十八:解决允许使用简单密码注册用户的问题
- 一步一步SharePoint 2007之十八:解决允许使用简单密码注册用户的问题
- 一步一步SharePoint 2007之十八:解决允许使用简单密码注册用户的问题
- HASH表中解决冲突的方法(链址法)————双链表
- 在C#单元测试中使用HttpContext的简单解决办法
- 一步一步SharePoint 2007之十八:解决允许使用简单密码注册用户的问题
- doxygen无法使用dot简单解决方法
- 项目同时使用Prototypet和jQuery冲突解决方法
- 默认库“library”与其他库的使用冲突;请使用 /NODEFAULTLIB:library LNK4098 的解决办法