简单HashTable实现

纸上得来终觉浅,所以我还是手动敲了一遍.懂了一点.2333333333333

直接看代码和注释:

<?php
/**
* store the hash data
*/
class HashNode{
public $key;
public $value;
public \(nextNode; public function __construct(\)key,\(value,\)nextNode=null){
$this->key = $key;
$this->value = $value;
$this->nextNode = $nextNode;
}
}

class HashTable{
# 存放数据
private $buckets;
# 数组大小
private $size = 10;
# 实例化时新建一个SPLFixedArray
public function __construct(){
# 使用SplFixedArray是因为其接近C语言的数组,效率也高
# 使用该标准库函数需要给定一个数组大小
\(this->buckets = new SplFixedArray(\)this->size);
}
# hash enpty function
private function hashfunc($key){
# count the key length
\(strlen = strlen(\)key);
# total
\(hashval = 0; for (\)i=0; $i < $strlen; $i++) {
# add the ascii of the word to total
\(hashval += ord(\)key{\(i}); } # return the remainder,serve as buckets key return (\)hashval % \(this->size); } # insert the value to the buckets public function insert(\)key,\(val){ # got the "\)key" of the key
$index = \(this->hashfunc(\)key);
# if this "\(key" in the buckets have data, # insert the data to the hashnode,not buckets if(isset(\)this->buckets[$index]))
{
\(newNode = new \HashNode(\)key,\(val,\)this->buckets[\(index]); // print_r(\)newNode);
}else{
\(newNode = new \HashNode(\)key,\(val,null); // print_r(\)newNode);
}
\(this->buckets[\)index] = $newNode;
}

public function find(\(key){ # got index by hanhfunc(\)key)
$index = \(this->hashfunc(\)key);
# 英语不会了用回中文吧.
# 拿当前这个key去取hashnode
$current = \(this->buckets[\)index];
while (isset(\(current)) { # 当前的对象的key和传进来的\)key相同
if($current->key == $key)
{
//find success
//则查找成功
return $current->value;
}
# 否则查找对象里nextNode
$current = $current->nextNode;
}
# 查找失败
return null;//find fail
// return \(this->buckets[\)index];
}

}

$hash = new HashTable();
# hash表冲突
# 原因:不同的关键字通过hash函数计算出来的hash值相同.
# 解决:开放定位法和拉链法
# 拉链法:
# 将所有hash值相同的关键字节点链接在同一个链表中.
$hash->insert('test1','123456');
$hash->insert('test12','abcdef');
$hash->insert('test123','test123');

echo $hash->find('test1');
echo $hash->find('test12');

posted @ 2018-04-22 12:19  Masker。  阅读(116)  评论(0)    收藏  举报