PHP头条
热点:

用PHP实现的HashTable及说明


最近在看凹凸曼和白菜写的书,500多页,其实我真正想看的是PHP扩展部分以及缓存部分。下面是凹凸曼用PHP实现的HashTable代码,其中需要说明的有两点:
1)代码中使用了 SplFixedArray ,这是一个更接近C语言的数组[Array],而且效率更高。使用之前需要开启SPL扩展,PHP5.3+默认开启。
2)代码中使用拉链法解决冲突,即将所有相同的Hash值的关键字节点链接在同一个链表中。

  1. php
  2. class HashNode {
  3. public $key;
  4. public $value;
  5. public $nextNode;
  6.  
  7. public function __construct($key, $value, $nextNode = NULL) {
  8. $this->key = $key;
  9. $this->value = $value;
  10. $this->nextNode = $nextNode;
  11. }
  12. }
  13. //天涯PHP博客 http://blog.phpha.com
  14. class HashTable {
  15. private $buckets;
  16. private $size = 10;
  17.  
  18. public function __construct() {
  19. $this->buckets = new SplFixedArray($this->size);
  20. }
  21.  
  22. private function hashfunc($key) {
  23. $strlen = strlen($key);
  24. $hashval = 0;
  25. for ($i = 0; $i < $strlen; $i++) {
  26. $hashval += ord($key{$i});
  27. }
  28. return $hashval % $this->size;
  29. }
  30.  
  31. public function insert($key, $value) {
  32. $index = $this->hashfunc($key);
  33. /* 新创建一个节点 */
  34. if (isset($this->buckets[$index])) {
  35. $newNode = new HashNode($key, $value, $this->buckets[$index]);
  36. } else {
  37. $newNode = new HashNode($key, $value, NULL);
  38. }
  39. $this->buckets[$index] = $newNode; /* 保存新节点 */
  40. }
  41.  
  42. public function find($key) {
  43. $index = $this->hashfunc($key);
  44. $current = $this->buckets[$index];
  45. while (isset($current)) { /* 遍历当前链表 */
  46. if ($current->key == $key) { /* 比较当前节点的关键字 */
  47. return $current->value; /* 查找成功 */
  48. }
  49. $current = $current->nextNode; /* 比较下一个节点 */
  50. }
  51. return NULL; /* 查找失败 */
  52. }
  53. }
  54. //天涯PHP博客 http://blog.phpha.com
  55. //******* 下面是测试代码 *******
  56. $ht = new HashTable();
  57. $ht->insert('key1', 'value1');
  58. $ht->insert('key12', 'value12');
  59. echo $ht->find('key1');
  60. echo $ht->find('key12');
  61. ?>

www.phpzy.comtrue/phpmst/965.htmlTechArticle用PHP实现的HashTable及说明 最近在看凹凸曼和白菜写的书,500多页,其实我真正想看的是PHP扩展部分以及缓存部分。下面是凹凸曼用PHP实现的HashTable代码,其中需要说明的有两点: 1)代码...

相关文章

相关频道:

PHP之友评论

今天推荐