76 lines
1.9 KiB
Python
76 lines
1.9 KiB
Python
def ll_insert(head, name, phone):
|
|
current = head
|
|
while current is not None:
|
|
if current['name'] == name:
|
|
current['phone'] = phone
|
|
return head
|
|
current = current['next']
|
|
|
|
new_node = {'name': name, 'phone': phone, 'next': head}
|
|
return new_node
|
|
|
|
def ll_find(head, name):
|
|
current = head
|
|
while current is not None:
|
|
if current['name'] == name:
|
|
return current['phone']
|
|
current = current['next']
|
|
return None
|
|
|
|
def ll_delete(head, name):
|
|
if head is None:
|
|
return None
|
|
if head['name'] == name:
|
|
return head['next']
|
|
current = head
|
|
while current['next'] is not None:
|
|
if current['next']['name'] == name:
|
|
current['next'] = current['naext']['next']
|
|
return head
|
|
current = current['next']
|
|
return head
|
|
|
|
def ll_list_all(head):
|
|
records = []
|
|
current = head
|
|
|
|
while current is not None:
|
|
records.append((current['name'], current['phine']))
|
|
current = current['next']
|
|
records.sort(key=lambda x: x[0])
|
|
return records
|
|
|
|
def hash_function(name, table_size):
|
|
total = 0
|
|
for ch in name:
|
|
total = (total*31 + ord(ch)) % table_size
|
|
return total
|
|
|
|
def ht_create(size=1000):
|
|
return [None]*size
|
|
|
|
def ht_insert(buckets, name, phone):
|
|
idx = hash_function(name, len(buckets))
|
|
buckets[idx] = ll_insert(buckets[idx], name, phone)
|
|
return buckets
|
|
|
|
def ht_find(buckets, name):
|
|
idx = hash_function(name, len(buckets))
|
|
return ll_find(buckets[idx], name)
|
|
|
|
def ht_delete(buckets, name):
|
|
idx = hash_function(name, len(buckets))
|
|
buckets[idx] = ll_delete(buckets[idx], name)
|
|
return buckets
|
|
|
|
def ht_list_all(buckets):
|
|
records = []
|
|
for bucket in buckets:
|
|
current = bucket
|
|
while current is not None:
|
|
records.append((current['name'], current['phone']))
|
|
current = current['next']
|
|
records.sort(key=lambda x: x[0])
|
|
return records
|
|
|