2026-rff_mp/groshevava/docs/data/linked_list.py

64 lines
1.9 KiB
Python

#Телефонного справочник - связный список
#создаёт новый узел
def ll_create_node(name, phone):
return {'name': name, 'phone': phone, 'next': None}
#добавляет запись в конец списка или обновляет.
def ll_insert(head, name, phone):
new_node = ll_create_node(name, phone)
if head is None:
return new_node
if head['name'] == name:
new_node['next'] = head['next']
return new_node
current = head
while current['next'] is not None:
if current['next']['name'] == name:
new_node['next'] = current['next']['next']
current['next'] = new_node
return head
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']
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
#собирает все записи связного списка в список name-phone, сортирует по имени
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