举一个例子,创建一个哈希表
时间: 2023-06-25 14:03:15 浏览: 47
好的,以下是一个用 Python 语言创建哈希表的例子:
```python
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self, key, data):
hash_value = self.hash_function(key, len(self.slots))
if self.slots[hash_value] is None:
self.slots[hash_value] = key
self.data[hash_value] = data
else:
if self.slots[hash_value] == key:
self.data[hash_value] = data
else:
next_slot = self.rehash(hash_value, len(self.slots))
while self.slots[next_slot] is not None and self.slots[next_slot] != key:
next_slot = self.rehash(next_slot, len(self.slots))
if self.slots[next_slot] is None:
self.slots[next_slot] = key
self.data[next_slot] = data
else:
self.data[next_slot] = data
def get(self, key):
start_slot = self.hash_function(key, len(self.slots))
data = None
stop = False
found = False
position = start_slot
while self.slots[position] is not None and not found and not stop:
if self.slots[position] == key:
found = True
data = self.data[position]
else:
position = self.rehash(position, len(self.slots))
if position == start_slot:
stop = True
return data
def hash_function(self, key, size):
return key % size
def rehash(self, old_hash, size):
return (old_hash + 1) % size
```
这个哈希表使用了线性探测法来处理冲突,具体实现过程可以看代码中的注释。你可以通过以下代码测试这个哈希表的功能:
```python
h = HashTable()
h.put(54, "cat")
h.put(26, "dog")
h.put(93, "lion")
h.put(17, "tiger")
h.put(77, "bird")
h.put(31, "cow")
h.put(44, "goat")
h.put(55, "pig")
h.put(20, "chicken")
print(h.slots)
print(h.data)
print(h.get(20))
print(h.get(17))
print(h.get(55))
h.put(20, "duck")
print(h.get(20))
```
输出结果为:
```
[77, 44, 55, 20, 26, 93, 17, None, None, 31, 54]
['bird', 'goat', 'pig', 'chicken', 'dog', 'lion', 'tiger', None, None, 'cow', 'cat']
chicken
tiger
pig
duck
```
这个哈希表使用了除留余数法来计算哈希值,并且在处理冲突时使用了线性探测法。你可以通过修改代码中的哈希函数和处理冲突的方法来实现其他的哈希表实现方式。