PHP实现 拉链式哈希表

来源:互联网 发布:淘宝店铺单品分析软件 编辑:程序博客网 时间:2024/05/17 06:17
<?php/** * 使用PHP语言实现数据的 拉链式哈希 存储 * @author beggar 770793038@qq.com * @date 2015-05-08 */class hashTable{    private $size;    private $bucket;    private $count = 0;    public function __construct($size) {        $this->size = $size;        $this->bucket = new SplFixedArray($this->size);    }    /**     * 取每个字符的asc码之和并对其取余,实现简单的散列函数     * @param type $key     * @return boolean     */    private function hashKey($key){        if(empty($key)){            return false;        }        $hash = 0;        $len = strlen($key);        for($i=0; $i<$len; $i++){            $hash += ord($key[$i]);        }        return $hash%$this->size;    }    /**     * 向哈希表中插入指定数据     * @param type $key     * @param type $val     * @return boolean     */    public function insert($key, $val=''){        if(empty($key) || empty($val)){            return false;        }        $index = $this->hashKey($key);        if($this->bucket[$index]->key == $key || $this->count >= $this->size){            return false;        }        if(isset($this->bucket[$index])){            $hashnode = new hashNode($key, $val, $this->bucket[$index]);        }else{            $hashnode = new hashNode($key, $val, NULL);        }        $this->bucket[$index] = $hashnode;        $this->count++;    }    /**     * 查找数据     * @param type $key     * @return boolean     */    public function find($key){        if(empty($key)){            return false;        }        $index = $this->hashKey($key);        $pHead = $this->bucket[$index];        while($pHead->key != $key){            $pHead = $pHead->next;        }        return $pHead->value;    }}/** * 使用类充当哈希表的每个节点,相当于C语言下的结构体实现的节点 */class hashNode{    public $key;    public $value;    public $next;    public function __construct($key, $val, $node=null) {        $this->key = $key;        $this->value = $val;        $this->next = $node;    }}

0 0
原创粉丝点击