zoukankan      html  css  js  c++  java
  • php 实现hash表

    hash表又称散列表,通过把关键字key经过hash函数映射到hash表中某个位置获取记录。

    存放记录的数组又称为hash表,映射函数称为hash函数

    下面是php中实现hash表的方法

    <?php
    /*hash表又称散列表,通过把关键字key经过hash函数映射到hash表中某个位置获取记录。
     * 
     * 存放记录的数组就是hash表
     *  
    */
    class hashtable{
    	private $buckets;//存储数据的数组
    	private $size = 10;//数组长度
    	
    	public function __construct(){//hash表数组初始化
    		$this->buckets = new SplFixedArray($this->size);
    	}
    	/*=====hash函数=====*/
    	private function hashfun($key){
    		$strlen = strlen($key);
    		$hashval = 0;
    		for($i=0;$i<$strlen;$i++){
    			$hashval+=ord($key[$i]);
    		}
    		
    		return $hashval%$this->size;
    	}
    	
    	/*=====hash插入操作=====*/
    	public function insert($key,$val){
    		$index = $this->hashfun($key);
    		if(isset($this->buckets[$index])){
    			$newnode = new hashnode($key, $val,$this->buckets[$index]);//新增值在头部
    		}else{
    			$newnode = new hashnode($key, $val);
    		}
    		$this->buckets[$index] = $newnode;
    	}
    	
    	/*=====hash表取值操作=====*/
    	public function find($key){
    		$index = $this->hashfun($key);
    		$current = $this->buckets[$index];
    		
    		while(isset($current)){
    			if($current->key == $key){
    				return $current->value;
    			}
    			$current = $current->nextnode;
    		}
    		return NULL;
    	}
    }
    
    //拉链法解决冲突
    class hashnode{
    	public $key;
    	public $value;
    	public $nextnode;
    	
    	public function __construct($key,$value,$nextnode=NULL){
    		$this->key = $key;
    		$this->value = $value;
    		$this->nextnode = $nextnode;
    	}
    }
    
    $m = new hashtable();
    $m->insert('key1', 'value1');
    $m->insert('key12', 'value2');
    echo $m->find('key1');
    echo $m->find('key12');
    
    
    ?>
    

      

  • 相关阅读:
    钱多多软件制作04
    团队项目01应用场景
    HDU 4411 arrest
    HDU 4406 GPA
    HDU 3315 My Brute
    HDU 3667 Transportation
    HDU 2676 Matrix
    欧拉回路三水题 POJ 1041 POJ 2230 POJ 1386
    SPOJ 371 BOXES
    POJ 3422 Kaka's Matrix Travels
  • 原文地址:https://www.cnblogs.com/taijun/p/3977885.html
Copyright © 2011-2022 走看看