散列表的构造方式 用代码表示
时间: 2023-06-02 14:06:21 浏览: 55
散列表是一种常见的数据结构,它通过一个哈希函数将键映射到一个位置,以实现快速的查找、插入和删除操作。构造散列表的方式有多种,常见的有拉链法、开放寻址法等。
下面是使用拉链法构造散列表的示例代码:
```python
class ListNode:
def __init__(self, key, val, next=None):
self.key = key
self.val = val
self.next = next
class HashTable:
def __init__(self, capacity=100):
self.capacity = capacity
self.buckets = [None] * capacity
def put(self, key, val):
hash_value = hash(key) % self.capacity
if not self.buckets[hash_value]:
self.buckets[hash_value] = ListNode(key, val)
else:
node = self.buckets[hash_value]
while node:
if node.key == key:
node.val = val
return
if not node.next:
break
node = node.next
node.next = ListNode(key, val)
def get(self, key):
hash_value = hash(key) % self.capacity
node = self.buckets[hash_value]
while node:
if node.key == key:
return node.val
node = node.next
return None
def remove(self, key):
hash_value = hash(key) % self.capacity
if not self.buckets[hash_value]:
return
if self.buckets[hash_value].key == key:
self.buckets[hash_value] = self.buckets[hash_value].next
return
node = self.buckets[hash_value]
while node.next:
if node.next.key == key:
node.next = node.next.next
return
node = node.next
# 使用示例
ht = HashTable()
ht.put("apple", 3)
ht.put("banana", 2)
ht.put("cherry", 5)
ht.put("apple", 4)
print(ht.get("apple"))
print(ht.get("banana"))
print(ht.get("cherry"))
ht.remove("banana")
print(ht.get("banana"))
```