链表法
- 通过建立链表来保存数据;
- 发生冲撞就将数据保存在重装地址的后一个节点中;
代码
class Node:
def __init__(self, value):
self.value = value
self.next = None
def create_table(num, hash_table):
mod_index = num % len(hash_table)
ptr = hash_table[mod_index]
if not ptr.next:
ptr.next = Node(num)
else:
while ptr.next:
ptr = ptr.next
ptr.next = Node(num)
def Print_all(head_ptr, i):
print(i, ":", end="\t")
while head_ptr:
print(head_ptr.value, end="\t")
head_ptr = head_ptr.next
print()
if __name__ == '__main__':
data_all = [16, 12, 5, 10, 8, 90, 63]
hash_tables = [Node(i) for i in range(10)]
for num in data_all:
create_table(num, hash_tables)
for i in range(10):
if hash_tables[i].next:
Print_all(hash_tables[i].next, i)
else:
print(i, ":", None)