80 lines
2.4 KiB
Python
80 lines
2.4 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': None}
|
|||
|
|
|
|||
|
|
# Если список пуст, новый узел становится головой
|
|||
|
|
if head is None:
|
|||
|
|
return new_node
|
|||
|
|
|
|||
|
|
# Иначе проходим в конец и вставляем
|
|||
|
|
current = head
|
|||
|
|
while current['next'] is not None:
|
|||
|
|
current = current['next']
|
|||
|
|
current['next'] = new_node
|
|||
|
|
return head
|
|||
|
|
|
|||
|
|
|
|||
|
|
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']
|
|||
|
|
|
|||
|
|
prev = head
|
|||
|
|
current = head['next']
|
|||
|
|
while current is not None:
|
|||
|
|
if current['name'] == name:
|
|||
|
|
prev['next'] = current['next']
|
|||
|
|
return head
|
|||
|
|
prev = current
|
|||
|
|
current = current['next']
|
|||
|
|
return head
|
|||
|
|
|
|||
|
|
|
|||
|
|
def ll_list_all(head):
|
|||
|
|
records = []
|
|||
|
|
current = head
|
|||
|
|
while current is not None:
|
|||
|
|
records.append((current['name'], current['phone']))
|
|||
|
|
current = current['next']
|
|||
|
|
records.sort(key=lambda x: x[0])
|
|||
|
|
return records
|
|||
|
|
|
|||
|
|
|
|||
|
|
# --------------------- Тестирование связного списка ---------------------
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
print("=== Тестирование связного списка ===")
|
|||
|
|
head = None
|
|||
|
|
|
|||
|
|
head = ll_insert(head, "Ivan", "123-456")
|
|||
|
|
head = ll_insert(head, "Boris", "789-012")
|
|||
|
|
head = ll_insert(head, "Anna", "345-678")
|
|||
|
|
head = ll_insert(head, "Ivan", "111-222") # обновление
|
|||
|
|
|
|||
|
|
print("Все записи:", ll_list_all(head))
|
|||
|
|
print("Телефон Ivan:", ll_find(head, "Ivan"))
|
|||
|
|
print("Телефон Boris:", ll_find(head, "Boris"))
|
|||
|
|
print("Телефон Noname:", ll_find(head, "Noname"))
|
|||
|
|
|
|||
|
|
head = ll_delete(head, "Boris")
|
|||
|
|
print("После удаления Boris, все записи:", ll_list_all(head))
|