您的位置:首页 > 编程语言 > PHP开发

使用拉链法解决冲突的简单hash表

2016-09-29 00:00 330 查看
摘要: 使用拉链法解决冲突的简单hash表

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'));

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php Hash表 拉链法