php实现哈希表

来源:互联网 发布:.us域名查询 编辑:程序博客网 时间:2024/06/06 08:48

看书看到一个算法,觉得挺妙的。用拉链法解决哈希值冲突


<?php //建结点class hashNope{public $key;public $value;public $nextNope;public function __construct($key,$value,$nextNope=null){$this->key=$key;$this->value=$value;$this->nextNope=$nextNope;}}//建一个哈希表class hashTable{private  $buckets;private $size=10;public function __construct(){$this->buckets=new SplFixedArray($this->size);//SplFixedArray()与array()作用一样,但效率更快}//用了最简单的哈希算法,把关键字的所有字符串加起来再取余private function hashfunc($key){$len=strlen($key);$hashval=0;for($i=0;$i<$len;$i++){$hashval+= ord($key{$i});}return $hashval % $this->size;}//插入算法public function insert($key,$value){$index= $this->hashfunc($key);if(isset($this->buckets[$index])){$nope= new hashNope($key, $value,$this->buckets[$index]);}else {$nope= new hashNope($key, $value,null);}$this->buckets[$index]=$nope;}//查找算法public function find($key){$index=$this->hashfunc($key);$current=$this->buckets[$index];while (isset($current)){         //遍历当前链表if($current->key == $key){return $current->value;}else $current =$current->nextNope;}return false;}}$ht= new hashTable();$ht->insert('key1',' value1');$ht->insert('key12', 'value2');echo $ht->find('key1');echo $ht->find('key12');?>


原创粉丝点击