php 實現hash表

來源:互聯網
上載者:User

標籤: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表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.