1. 程式人生 > >PHP實現一個hash表(拉鍊法解決hash衝突)程式碼例項

PHP實現一個hash表(拉鍊法解決hash衝突)程式碼例項

<?php
header('Content-type:text/html;charset=utf-8');

class HashTable{
    private $buckets;
    private $size = 10;
    public function __construct()
    {
        $this->buckets = new SplFixedArray($this->size);
    }

    private function hash_func($key)
    {
        $strlen = strlen($key);
        $hash_val = 0;
        for ($i=0;$i<$strlen;$i++){
            $hash_val += ord($key[$i]);
        }
        return $hash_val%$this->size;
    }

    public function insert($key,$val)
    {
        $index = $this->hash_func($key);
        if(isset($this->buckets[$index])){
            $new_code = new HashNode($key,$val,$this->buckets[$index]);
        }else{
            $new_code = new HashNode($key,$val,null);
        }
        $this->buckets[$index] = $new_code;
    }

    public function find($key)
    {
        $index = $this->hash_func($key);
        $current = $this->buckets[$index];
        while (isset($current)) {
            if ($current->key == $key){
                return $current->value;
            }
            $current = $current->next_node;
        }
        return null;
    }
}

class HashNode{
    public $key;
    public $value;
    public $next_node;
    public function __construct($key,$value,$next_node=null)
    {
        $this->key = $key;
        $this->value = $value;
        $this->next_node = $next_node;
    }


}

$hash = new HashTable();
$hash->insert('value1','A');
$hash->insert('value12','B');
//echo $hash->find('value1');
//echo $hash->find('value2');
echo $hash->find('value1');
echo $hash->find('value12');

記錄一下例項,有興趣的可以一起研究下。。。