哈希表
通过最简单的取模运算作为哈希算法
class HashNode(object):
def __init__(self, id, data):
self.id = id
self.data = data
self.next = None
def __str__(self):
return '(%d,%s)' % (self.id, str(self.data))
class HashLinkedList(object):
def __init__(self):
self.root = None
def add(self, node):
if self.root is None:
self.root = node
else:
temp = self.root
while temp.next is not None:
temp = temp.next
temp.next = node
def find(self, id):
if self.root is None:
return None
temp = self.root
while temp is not None:
if temp.id == id:
return temp
return None
def update(self, node):
if self.root is not None:
node = self.find(node.id)
if node is not None:
node.data = node.data
def delete(self, node):
if self.root is not None:
temp = self.root
if self.root.id == node.id:
self.root = self.root.next
return
while temp.next is not None:
if temp.next.id == node.id:
temp.next = temp.next.next
def list(self):
if self.root is not None:
temp = self.root
while temp is not None:
print(temp.data, end='->')
temp = temp.next
print()
else:
print("empty!")
class HashTable(object):
"""
哈希表又称散列表,是根据关键字key来加速访问的数据结构。
通过一个关键字key通过一个映射函数到达表中一个位置访问记录,
从而加快查询速度。而映射函数成为散列函数,存储记录的表成为散列表。
- 自实现一个简单哈希表采用数组+链表的形式
- 每一个数组维护了一个链表,链表中保存了具体数据
- 哈希算法采用了简单的取模算法
"""
def __init__(self):
self.size = 5
self.linked_list = [HashLinkedList() for i in range(self.size)]
def hash(self, id):
return id % self.size
def add(self, node):
self.linked_list[self.hash(node.id)].add(node)
def update(self, node):
self.linked_list[self.hash(node.id)].update(node)
def find(self, id):
return self.linked_list[self.hash(id)].find(id)
def delete(self, node):
self.linked_list[self.hash(node.id)].delete(node)
def list(self):
for l in self.linked_list:
l.list()
if __name__ == '__main__':
node1 = HashNode(1, 1)
node2 = HashNode(2, 2)
node3 = HashNode(3, 3)
node4 = HashNode(4, 4)
node5 = HashNode(5, 5)
node6 = HashNode(6, 6)
node7 = HashNode(7, 7)
node8 = HashNode(8, 8)
hash_table = HashTable()
hash_table.add(node1)
hash_table.add(node2)
hash_table.add(node3)
hash_table.add(node4)
hash_table.add(node5)
hash_table.add(node6)
hash_table.add(node7)
hash_table.add(node8)
hash_table.list()
node4.data = 666
hash_table.update(node4)
print("update ==== ")
hash_table.list()
print('find ====')
print(hash_table.find(3))
hash_table.delete(node3)
hash_table.delete(node4)
print("delete ---")
hash_table.list()