php实现哈希表

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


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


猜你喜欢

转载自blog.csdn.net/zengsihua/article/details/78428292