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

      

  • 相关阅读:
    JS_ECMA基本语法中的几种封装的小函数-1
    DOM_06之定时器、事件、cookie
    DOM_05之DOM、BOM常用对象
    OC数组中文排序
    uiwebview加载中文URL
    ios判断点击的坐标点
    获取字符串在另一个字符串中出现的次数
    NSFileHandle
    NSFileManager
    NSData
  • 原文地址:https://www.cnblogs.com/taijun/p/3977885.html
Copyright © 2011-2022 走看看