简单HashTable实现

纸上得来终觉浅,所以我还是手动敲了一遍.懂了一点.2333333333333

直接看代码和注释:

<?php
/**
 * store the hash data
 */
class HashNode{
    public $key;
    public $value;
    public $nextNode;
    public function __construct($key,$value,$nextNode=null){
        $this->key = $key;
        $this->value = $value;
        $this->nextNode = $nextNode;
    }
}

class HashTable{
    # 存放数据
    private $buckets;
    # 数组大小
    private $size = 10;
    # 实例化时新建一个SPLFixedArray
    public function __construct(){
        # 使用SplFixedArray是因为其接近C语言的数组,效率也高
        # 使用该标准库函数需要给定一个数组大小
        $this->buckets = new SplFixedArray($this->size);
    }
    # hash enpty function 
    private function hashfunc($key){
        # count the key length
        $strlen = strlen($key);
        # total
        $hashval = 0;
        for ($i=0; $i < $strlen; $i++) { 
            # add the ascii of the word to total
            $hashval += ord($key{$i});
        }
        # return the remainder,serve as buckets key
        return ($hashval % $this->size);
    }
    # insert the value to the buckets
    public function insert($key,$val){
        # got the "$key" of the key
        $index = $this->hashfunc($key);
        # if this "$key" in the buckets have data,
        # insert the data to the hashnode,not buckets
        if(isset($this->buckets[$index]))
        {
            $newNode = new \HashNode($key,$val,$this->buckets[$index]);
            // print_r($newNode);
        }else{
            $newNode = new \HashNode($key,$val,null);
            // print_r($newNode);
        }
        $this->buckets[$index] = $newNode;
    }

    public function find($key){
        # got index by hanhfunc($key)
        $index = $this->hashfunc($key);
        # 英语不会了用回中文吧.
        # 拿当前这个key去取hashnode
        $current = $this->buckets[$index];
        while (isset($current)) {
            # 当前的对象的key和传进来的$key相同
            if($current->key == $key)
            {
                //find success
                //则查找成功
                return $current->value;
            }
            # 否则查找对象里nextNode
            $current = $current->nextNode;
        }
        # 查找失败
        return null;//find fail
        // return $this->buckets[$index];
    }


}

$hash = new HashTable();
# hash表冲突
# 原因:不同的关键字通过hash函数计算出来的hash值相同.
# 解决:开放定位法和拉链法
# 拉链法:
#   将所有hash值相同的关键字节点链接在同一个链表中.
$hash->insert('test1','123456');
$hash->insert('test12','abcdef');
$hash->insert('test123','test123');

echo $hash->find('test1');
echo $hash->find('test12');

转载于:https://www.cnblogs.com/Masker/articles/8906452.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值