拉链法解决hashtable冲突问题

拉链法解决冲突。拉链法解决冲突的做法是将所有的相同Hash值的key放在一个链表中,比如key3和key14在hash之后都是0,那么在数组的键为0的地方存储这两个值,形式是链表。如果不能理解我的文字,请看下面的示例,看一下打印信息就明白了。拉链法是什么,就是链表。

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 $arr;
	private $size=10;
	public function __construct(){
		$this->arr = new SplFixedArray($this->size);
	}

	public function SimpleHash($key){
		$ascTotal=0;
		$strlen = strlen($key);
		for($i=0;$i<$strlen;$i++){
			$ascTotal+=ord($key[$i]);
		}
		return $ascTotal%$this->size;
	}
	//使用拉链法
	//将最新的放在前面
	public function set($key,$val){
		$hash = $this->SimpleHash($key);
		if(isset($this->arr[$hash])){
			$newNode = new HashNode($key,$val,$this->arr[$hash]);
		}else{
			$newNode= new HashNode($key,$val,null);
		}
		$this->arr[$hash] = $newNode;
		return true;
	}

	public function get($key){
		$hash = $this->SimpleHash($key);
		$current = $this->arr[$hash];
		while(!empty($current)){
			if($current->key == $key ){
				return $current->value;
			}
			$current = $current->nextNode;	
		}	
		return NULL;
	}
	public function getList(){
		return $this->arr;
	}
}
$newArr = new HashTable();
for($i=0;$i<25;$i++){
	$key = 'key'.$i;
	$newArr->set($key,$i);
}
$arr = $newArr->getList();
print_r($arr);

  

猜你喜欢

转载自www.cnblogs.com/zh718594493/p/12094098.html