hash算法与拉链法解决冲突

<?php
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;
    
    public function __construct()
    {
        $this->buckets = [];
    }
    
    private function hashfunc($key)
    {
        $strlen = strlen($key);
        $hashval = 0;
        for ($i = 0; $i < $strlen; $i++) {
            $hashval += ord($key[$i]);
        }
        return $hashval % $this->size;
    }
    
    public function insert($key, $value)
    {
        $index = $this->hashfunc($key);
        //新创建一个节点
        if (isset($this->buckets[$index])) {
            $newNode = new HashNode($key, $value, $this->buckets[$index]);
        } else {
            $newNode = new HashNode($key, $value, NULL);
        }
        $this->buckets[$index] = $newNode; //保存新节点
    }
    
    public function find($key)
    {
        $index = $this->hashfunc($key);
        $current = $this->buckets[$index];
        while (isset($current)) {
            if($current->key == $key){
                return $current->value;
            }
            var_dump($current);die;
            $current = $current->nextNode;
        }
        return NULL;
    }
}

解释:

1.使用Hash函数计算关键字的Hash值,通过Hash值定位到Hash表的指定位置

2.如果此位置已经被其他节点占用,把新节点的$nextNode指向此节点,否则把新节点的$nextNode设置为NULL

3.把新节点保存到Hash表的当前位置

4.遍历当前链表,比较链表中每个节点的关键字与查找关键字是否相等

猜你喜欢

转载自www.cnblogs.com/kerwing/p/9154865.html