栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

用PHP实现的HashTable及说明

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用PHP实现的HashTable及说明

用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 < $strlen; $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. ?>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/230142.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号