$this->buckets[$index] = $newNode; // 保存新节点 } public function find($key) { $index = $this->hashfunc($key); $current = $this->buckets[$index]; var_dump($current); while (isset($current)) { // 遍历当前链表 if ($current->key == $key) { // 比较当前节点的关键字 echo $key; return $current->value; // 查询成功 } $current = $current->nextNode; // 比较下一个节点 // var_dump($current); } return NULL; // 查询失败 } } $ht = new HashTable(); $ht->insert('key1', 'value1'); $ht->insert('key12', 'value12'); // 把$current的值覆盖 重新赋值 echo $ht->find('key1'); echo '<br/>'; echo $ht->find('key12');
} return null; } private function hashFunc($key) { $strLen = strlen($key); $hashval = 0; for ($i = 0; $i < $strLen; $i++) { $hashval += ord($key[$i]); } return $hashval % $this->size; } } class HashNode { public $key; public $value; public $nextNode; public function __construct($key, $value, $nextNode = null) { $this->key = $key; $this->value = $value; $this->nextNode = $nextNode; } } $hashTable = new HashTable(); $hashTable->insert('key1', 'value1'); $hashTable->insert('key12', 'value2'); echo $hashTable->find('key1'); echo ' '; echo $hashTable->find('key12');