HashTable實現程式碼分享

王大牛發表於2021-10-27
<?php
include 'HashNode.php';
/**
 * HashTable實現
 */
class HashTable 
{
    private $buckets;
    private $size = 10;

    public function __construct()
    {
        // SplFixedArray Object ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => )
        $this->buckets = new SplFixedArray($this->size);
    }

    /**
     * hash演算法
     *
     * @param string $key
     * @return void
     */
    private function hash($key)
    {
        $strlen = strlen($key);
        $hashval = 0;
        for($i=0;$i<$strlen;$i++)
        {
            // ord 返回 ASCII值
            $hashval += ord($key.$i);
        }

        return $hashval % $this->size;
    }

    /**
     * 新增資料
     *
     * @param string $key
     * @param string $val
     * @return void
     */
    public function add($key,$val)
    {
        // 生成 key
        $index = $this->hash($key);
        // 判斷當前key節點是否存在,存在返回
        if(isset($this->buckets[$index])) {
            $newNode = new HashNode($key,$val,$this->buckets[$index]);
        }else{
            // 不存在新增節點
            $newNode = new HashNode($key,$val,null);
        }
        // arr[$index] = $val
        $this->buckets[$index] = $newNode;
    }

    /**
     * 根據key獲取資料
     *
     * @param string $key
     * @return void
     */
    public function get($key)
    {
        $index = $this->hash($key);
        $current = $this->buckets[$index];
        // var_dump($current,$key);die;
        // D:\phpstudy_pro\WWW\phpcore\05-code\HashTable.php:68:
        // object(HashNode)[4]
        // public 'key' => string 'key2' (length=4)
        // public 'value' => string 'ass' (length=3)
        // public 'nextNode' => 
        //     object(HashNode)[3]
        //     public 'key' => string 'key1' (length=4)
        //     public 'value' => 
        //         array (size=2)
        //         0 => string 'zs' (length=2)
        //         1 => int 18
        //     public 'nextNode' => null
        // D:\phpstudy_pro\WWW\phpcore\05-code\HashTable.php:68:string 'key1' (length=4)
        while(isset($current)) {
            /**
             * key2 == key1 false
             * $current = $current->nextNode;
             * 此時$current->key = key1 
             * $current->key == $key
             */
            if($current->key == $key)
            {
                return $current->value;
            }
            $current = $current->nextNode;
        }
        return null;
    }
}
<?php

class HashNode
{
    public $key;
    public $value;
    public $nextNode;

    public function __construct($key,$value,$nextNode=null)
    {
        $this->key = $key;
        $this->value = $value;
        $this->nextNode = $nextNode;
    }
}
<?php

include 'HashTable.php';


$ht = new HashTable;
$ht->add('key1',['zs',18]);
$ht->add('key2','ass');

print_r($ht->get('key1'));
print_r($ht->get('key2'));

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章