PHP 实现HASH表
发布时间:2020-05-26 01:19:37 所属栏目:PHP 来源:互联网
导读:PHP 实现HASH表
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 classHashTable{
private$buckets; //用于存储数据的数组
private$size=12; //记录buckets数组的大小
publicfunction__construct(){
$this->buckets=newSplFixedArray($this->size);
//SplFixedArray效率更高,也可以用一般的数组来代替
}
privatefunctionhashfunc($key){
$strlen=strlen($key); //返回字符串的长度
$hashval=0;
for($i=0;$i<$strlen;$i++){
$hashval+=ord($key[$i]);//返回ASCII的值
}
return$hashval%$this->size;//返回取余数后的值
}
publicfunctioninsert($key,$value){
$index=$this->hashfunc($key);
if(isset($this->buckets[$index])){
$newNode=newHashNode($key,$value,$this->buckets[$index]);
}else{
$newNode=newHashNode($key,null);
}
$this->buckets[$index]=$newNode;
}
publicfunctionfind($key){
$index=$this->hashfunc($key);
$current=$this->buckets[$index];
echo"</br>";
var_dump($current);
while(isset($current)){//遍历当前链表
if($current->key==$key){//比较当前结点关键字
return$current->value;
}
$current=$current->nextNode;
//return$current->value;
}
returnNULL;
}
}
classHashNode{
public$key; //关键字
public$value; //数据
public$nextNode; //HASHNODE来存储信息
publicfunction__construct($key,$nextNode=NULL){
$this->key=$key;
$this->value=$value;
$this->nextNode=$nextNode;
}
}
$ht=newHashTable();
$ht->insert('key1','value1');
//$ht->insert('key12','value12');
echo$ht->find('key1');
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
