使用php实现hash链表
<?php
class HashTable{
private $buckets;
private $size=10;
public function __construct(){
$this->buckets = new SplFixedArray($this->size);
}
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;//查找成功
}
$current = $current->nextNode;//比较下一个节点
}
return null;
}
}
class HashNode{
public $key;
public $value;
public $nextNode;
public function __construct($key,$value,$nextNode=null){
$this->key = $key;
$this->value = $value;
$this->nextNode = $nextNode;
}
}
$ht = new HashTable();
$ht->insert('key1','value1');
$ht->insert('key12','value2');
echo $ht->find('key1');
echo $ht->find('key12');