哈希表


class HashTable
{
    private $size;
    private $table;

    public function __construct($size = 10)
    {
        $this->size = $size;
        $this->table = [];
    }

    private function getIndex($key)
    {
        return ord($key) % $this->size;
    }

    public function show()
    {
        print_r($this->table);
    }

    public function get($key)
    {
        $index = $this->getIndex($key);

        if (!isset($this->table[$index])) {
            return null;
        }

        // 这里可能会产生冲突,需要再维护一个链表
        return $this->table[$index][$key];
    }

    public function set($key, $value)
    {
        $index = $this->getIndex($key);

        // 这里可能会产生冲突,需要再维护一个链表
        $this->table[$index][$key] = $value;

        return true;
    }
}

results matching ""

    No results matching ""