• 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');
     
     
    ?>
  • 相关阅读:
    react-native 调用原生方法
    react-native 生命周期
    查看ubuntu系统信息
    Python之DataFrame将列作为索引
    Python之读取文本文件
    Python 之 直接赋值、Deepcopy、Copy区别
    Python之time与datetime模块
    Python之连接MySQL数据库,执行建表语句
    Python之读取csv文件
    MySQL之count() 函数
  • 原文地址:https://www.cnblogs.com/myJuly/p/13577543.html
Copyright © 2020-2023  润新知