最近在看凹凸曼和白菜寫的書,500多頁,其實我真正想看的是PHP擴展部分以及緩存部分。下面是凹凸曼用PHP實現的HashTable代碼,其中需要說明的有兩點:
1)代碼中使用了 SplFixedArray ,這是一個更接近C語言的數組[Array],而且效率更高。使用之前需要開啟SPL擴展,PHP5.3+默認開啟。
2)代碼中使用拉鏈法解決沖突,即將所有相同的Hash值的關鍵字節點鏈接在同一個鏈表中。
<?phphtml' target='_blank'>class HashNode { public $key; public $value; public $nextNode; public function __construct($key, $value, $nextNode = NULL) { $this->key = $key; $this->value = $value; $this->nextNode = $nextNode; }}//天涯PHP博客 http://blog.phpha.comclass 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); /* 新創建一個節點 www.it165.net */ 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; /* 查找失敗 */ }}//天涯PHP博客 http://blog.phpha.com//******* 下面是測試代碼 *******$ht = new HashTable();$ht->insert('key1', 'value1');$ht->insert('key12', 'value12');echo $ht->find('key1');echo $ht->find('key12');?>
原文地址: http://blog.phpha.com
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答