php 实现hash表
hash表又称散列表,通过把关键字key经过hash函数映射到hash表中某个位置获取记录。
存放记录的数组又称为hash表,映射函数称为hash函数
下面是php中实现hash表的方法
<?php
/*hash表又称散列表,通过把关键字key经过hash函数映射到hash表中某个位置获取记录。
*
* 存放记录的数组就是hash表
*
*/
class
hashtable{
private
$buckets
;
//存储数据的数组
private
$size
= 10;
//数组长度
public
function
__construct(){
//hash表数组初始化
$this
->buckets =
new
SplFixedArray(
$this
->size);
}
/*=====hash函数=====*/
private
function
hashfun(
$key
){
$strlen
=
strlen
(
$key
);
$hashval
= 0;
for
(
$i
=0;
$i
<
$strlen
;
$i
++){
$hashval
+=ord(
$key
[
$i
]);
}
return
$hashval
%
$this
->size;
}
/*=====hash插入操作=====*/
public
function
insert(
$key
,
$val
){
$index
=
$this
->hashfun(
$key
);
if
(isset(
$this
->buckets[
$index
])){
$newnode
=
new
hashnode(
$key
,
$val
,
$this
->buckets[
$index
]);
//新增值在头部
}
else
{
$newnode
=
new
hashnode(
$key
,
$val
);
}
$this
->buckets[
$index
] =
$newnode
;
}
/*=====hash表取值操作=====*/
public
function
find(
$key
){
$index
=
$this
->hashfun(
$key
);
$current
=
$this
->buckets[
$index
];
while
(isset(
$current
)){
if
(
$current
->key ==
$key
){
return
$current
->value;
}
$current
=
$current
->nextnode;
}
return
NULL;
}
}
//拉链法解决冲突
class
hashnode{
public
$key
;
public
$value
;
public
$nextnode
;
public
function
__construct(
$key
,
$value
,
$nextnode
=NULL){
$this
->key =
$key
;
$this
->value =
$value
;
$this
->nextnode =
$nextnode
;
}
}
$m
=
new
hashtable();
$m
->insert(
'key1'
,
'value1'
);
$m
->insert(
'key12'
,
'value2'
);
echo
$m
->find(
'key1'
);
echo
$m
->find(
'key12'
);
?>