80 lines
2.5 KiB
Plaintext
80 lines
2.5 KiB
Plaintext
Linked List Phone Book:
|
||
|
||
def ll_insert(head, name, phone):
|
||
new_node = {'name': name, 'phone' : phone, 'next': None}
|
||
if head is None:
|
||
return new_node
|
||
if head['name'] == name:
|
||
head['phone'] = phone
|
||
return head
|
||
current = head
|
||
while current['next'] is not None:
|
||
if current['next']['name'] == name:
|
||
current['next']['phone'] = phone
|
||
return head
|
||
current = current['next']
|
||
current['next'] = new_node
|
||
return head
|
||
def ll_find(head, name):
|
||
current = head
|
||
while current != 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['next']['next']
|
||
return head
|
||
current=current['next']
|
||
return head
|
||
def ll_list_all(head):
|
||
records= []
|
||
current = head
|
||
while current is not None:
|
||
records.append({'name': current['name'], 'phone': current['phone']})
|
||
current = current['next']
|
||
records.sort(key=lambda x: x['name'])
|
||
return records
|
||
def ll_print_all(head):
|
||
records = ll_list_all(head)
|
||
for record in records:
|
||
print(f"{record['name']}: {record['phone']}")
|
||
head = None
|
||
#добавление записей
|
||
print("\n1. Добавляем записи в список:")
|
||
head = ll_insert(head, "Анна", "123")
|
||
head = ll_insert(head, "Сергей", "234")
|
||
head = ll_insert(head, "Георгий", "345")
|
||
head = ll_insert(head, "Виктория", "456")
|
||
ll_print_all(head)
|
||
#Обновляем номер
|
||
print("\n2. Добавляем новую запись:")
|
||
head = ll_insert(head, "Антон", "666")
|
||
ll_print_all(head)
|
||
|
||
# Поиск записей
|
||
print(f"\n3. Производим поиск записей: \nПоиск Алисы: {ll_find(head, 'Анна')}")
|
||
print(f"Поиск Елены: {ll_find(head, 'Елена')}")
|
||
|
||
# Удаление записей
|
||
print("\n4. Удаляем Владимира:")
|
||
head = ll_delete(head, "Владимир")
|
||
ll_print_all(head)
|
||
|
||
print("\n5. Удаляем Антона:")
|
||
head = ll_delete(head, "Антон")
|
||
ll_print_all(head)
|
||
|
||
print("\n6. Пробуем удалить несуществующую запись:")
|
||
head = ll_delete(head, "Некто")
|
||
ll_print_all(head)
|
||
|
||
|