標籤:blog io ar for 資料 div sp cti log
hash表又稱散列表,通過把關鍵字key經過hash函數映射到hash表中某個位置擷取記錄。
存放記錄的數組又稱為hash表,映射函數稱為hash函數
下面是php中實現hash表的方法
<?php/*hash表又稱散列表,通過把關鍵字key經過hash函數映射到hash表中某個位置擷取記錄。 * * 存放記錄的數組就是hash表 * */class hashtable{private $buckets;//儲存資料的數組private $size = 10;//數組長度public function __construct(){//hash表數組初始化$this->buckets = new SplFixedArray($this->size);}/*=====hash函數=====*/private function hashfun($key){$strlen = strlen($key);$hashval = 0;for($i=0;$i<$strlen;$i++){$hashval+=ord($key[$i]);}return $hashval%$this->size;}/*=====hash插入操作=====*/public function insert($key,$val){$index = $this->hashfun($key);if(isset($this->buckets[$index])){$newnode = new hashnode($key, $val,$this->buckets[$index]);//新增值在頭部}else{$newnode = new hashnode($key, $val);}$this->buckets[$index] = $newnode;}/*=====hash表取值操作=====*/public function find($key){$index = $this->hashfun($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;}}$m = new hashtable();$m->insert(‘key1‘, ‘value1‘);$m->insert(‘key12‘, ‘value2‘);echo $m->find(‘key1‘);echo $m->find(‘key12‘);?>
php 實現hash表