[1] Add hash table

This commit is contained in:
anikinvd 2026-05-22 17:49:33 +00:00
parent b6debe4706
commit a3c64db4af

View File

@ -6,12 +6,9 @@ def llist_insert(head, name, phone):
current['phone'] = phone current['phone'] = phone
return head return head
current = current['next'] current = current['next']
new_node = {'name': name, 'phone': phone, 'next': None} new_node = {'name': name, 'phone': phone, 'next': None}
if head is None: if head is None:
return new_node return new_node
current = head current = head
while current['next'] is not None: while current['next'] is not None:
current = current['next'] current = current['next']
@ -31,10 +28,8 @@ def llist_find(head, name):
def llist_delete(head, name): def llist_delete(head, name):
if head is None: if head is None:
return None return None
if head['name'] == name: if head['name'] == name:
return head['next'] return head['next']
prev = head prev = head
current = head['next'] current = head['next']
while current is not None: while current is not None:
@ -56,12 +51,47 @@ def llist_get_all(head):
return entries return entries
BUCKET_SIZE = 1000
def ht_create():
return [None] * BUCKET_SIZE
def ht_insert(table, name, phone):
idx = hash(name) % len(table)
table[idx] = llist_insert(table[idx], name, phone)
return table
def ht_find(table, name):
idx = hash(name) % len(table)
return llist_find(table[idx], name)
def ht_delete(table, name):
idx = hash(name) % len(table)
table[idx] = llist_delete(table[idx], name)
return table
def ht_get_all(table):
all_entries = []
for head in table:
current = head
while current is not None:
all_entries.append((current['name'], current['phone']))
current = current['next']
all_entries.sort(key=lambda x: x[0])
return all_entries
if __name__ == '__main__': if __name__ == '__main__':
head = None table = ht_create()
head = llist_insert(head, "Alice", "111-222") ht_insert(table, "Alice", "111-222")
head = llist_insert(head, "Bob", "333-444") ht_insert(table, "Bob", "333-444")
head = llist_insert(head, "Alice", "555-666") ht_insert(table, "Alice", "555-666")
print(llist_find(head, "Alice")) print(ht_find(table, "Alice"))
print(llist_find(head, "Charlie")) print(ht_find(table, "Bob"))
head = llist_delete(head, "Bob") print(ht_find(table, "Charlie"))
print(llist_get_all(head)) ht_delete(table, "Bob")
print(ht_get_all(table))