ITPub博客

首页 > IT职业 > IT图书 > 用PHP实现的HashTable及说明

用PHP实现的HashTable及说明

IT图书 作者:flbwhx 时间:2021-09-09 09:22:15 0 删除 编辑

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

  1. classHashNode{

  2. public $key;

  3. public $value;

  4. public $nextNode;

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

  6. $this->key = $key;

  7. $this->value = $value;

  8. $this->nextNode = $nextNode;

  9. }

  10. }

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

  12. classHashTable{

  13. private $buckets;

  14. private $size =10;

  15. publicfunction __construct(){

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

  17. }

  18. privatefunction hashfunc($key){

  19. $strlen = strlen($key);

  20. $hashval =0;

  21. for($i =0; $i

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

  23. }

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

  25. }

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

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

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

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

  30. }else{

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

  32. }

  33. $this->buckets[$index]= $newNode;

  34. }

  35. publicfunction find($key){

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

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

  38. while(isset($current)){

  39. if($current->key == $key){

  40. return $current->value;

  41. }

  42. $current = $current->nextNode;

  43. }

  44. return NULL;

  45. }

  46. }

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

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

  49. $ht =newHashTable();

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

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

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

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

  54. ?>


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/933/viewspace-2802752/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: PHP内核
请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    92
  • 访问量
    671