Zipper method to solve the conflict hashtable

Zipper method to solve the conflict. Zipper method of conflict resolution practice is key to all of the same Hash value in a list, such as key3 and key14 after the hash is 0, then the value is stored in two places at the 0 key array form a linked list . If you can not understand my words, look at the following example, look at the print information to understand. What zipper method is that list.

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);

  

Guess you like

Origin www.cnblogs.com/zh718594493/p/12094098.html