使用拉链法解决冲突的简单hash表

本文介绍了一种使用PHP实现的简单哈希表数据结构,并采用拉链法解决冲突。通过具体的代码示例展示了如何插入、查找元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 Hash函数的作用是把任意长度的输入,通过hash算法变换成固定长度的输出,该输出就是hash值,hash表的复杂度为O(1)。

<?php 
/**
 * 一个简单的hash表
 * 使用拉链法解决冲突
 */
class hashtable{
	private $buckets;   //存储数据数组
	private $size = 10;

	public function __construct(){
		$this -> buckets = new SplFixedArray($this->size);
	}
	/**
	 * 通过把字符串相加取余得到hash值
	 * @param  string $key 关键字
	 * @return int         hash值
	 */
	private function hashfunc($key){
		$strlen  = strlen($key);
		$hashval = 0;
		for ($i=0; $i < $strlen; $i++) { 
			$hashval += ord($key[$i]);
		}
		return $hashval%$this->size;
	}
	/**
	 * 1. 使用hsahfuc计算关键字的hash值,通过hash值定位到hash表的指定位置
	 * 2. 如果此位置已经被占用,把新节点的$NextNode指向此节点,否则把$NextNode设置为NULL
	 * 3. 把新节点保存到hash表中
	 * @param  string $key   关键字
	 * @param  string $value 值
	 * @return void        
	 */
	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;
			}
			$current = $current->nextNode;
		}
	}
}

class HashNode{
	public $key;            //节点关键字
	public $value;          //节点的值
	public $nextNode;       //具有相同hash值的节点的指针
	public function __construct($key,$value,$nextNode=null){
		$this -> key      = $key;
		$this -> value    = $value;
		$this -> nextNode = $nextNode;
	}
}

$test = new hashtable();
$test -> insert('key1','value1');
$test -> insert('key12','value12');
$test -> insert('key2','value2');
var_dump($test -> find('key1'));
var_dump($test -> find('key12'));
var_dump($test -> find('key2'));

 ?>

 

转载于:https://my.oschina.net/liangwt/blog/753497

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值