用PHP实现的HashTable代码,其中需要说明的有两点:
1)代码中使用了 SplFixedArray ,这是一个更接近C语言的数组[Array],而且效率更高。使用之前需要开启SPL扩展,PHP5.3+默认开启。
2)代码中使用拉链法解决冲突,即将所有相同的Hash值的关键字节点链接在同一个链表中。

  1. <?php

  2. classHashNode{

  3. public $key;

  4. public $value;

  5. public $nextNode;

  6. publicfunction __construct($key, $value, $nextNode = NULL){

  7. $this->key = $key;

  8. $this->value = $value;

  9. $this->nextNode = $nextNode;

  10. }

  11. }

  12. //天涯PHP博客 http://blog.phpha.com

  13. classHashTable{

  14. private $buckets;

  15. private $size =10;

  16. publicfunction __construct(){

  17. $this->buckets =newSplFixedArray($this->size);

  18. }

  19. privatefunction hashfunc($key){

  20. $strlen = strlen($key);

  21. $hashval =0;

  22. for($i =0; $i < $strlen; $i++){

  23. $hashval += ord($key{$i});

  24. }

  25. return $hashval % $this->size;

  26. }

  27. publicfunction insert($key, $value){

  28. $index = $this->hashfunc($key);

  29. /* 新创建一个节点 */

  30. if(isset($this->buckets[$index])){

  31. $newNode =newHashNode($key, $value, $this->buckets[$index]);

  32. }else{

  33. $newNode =newHashNode($key, $value, NULL);

  34. }

  35. $this->buckets[$index]= $newNode;/* 保存新节点 */

  36. }

  37. publicfunction find($key){

  38. $index = $this->hashfunc($key);

  39. $current = $this->buckets[$index];

  40. while(isset($current)){/* 遍历当前链表 */

  41. if($current->key == $key){/* 比较当前节点的关键字 */

  42. return $current->value;/* 查找成功 */

  43. }

  44. $current = $current->nextNode;/* 比较下一个节点 */

  45. }

  46. return NULL;/* 查找失败 */

  47. }

  48. }

  49. //天涯PHP博客 http://blog.phpha.com

  50. //******* 下面是测试代码 *******

  51. $ht =newHashTable();

  52. $ht->insert('key1','value1');

  53. $ht->insert('key12','value12');

  54. echo $ht->find('key1');

  55. echo $ht->find('key12');

  56. ?>