2026-rff_mp/nehoroshevaa/Task 1/code/LinkedList.py

62 lines
1.8 KiB
Python
Raw Normal View History

2026-04-29 15:05:19 +00:00
def ll_insert(head, name, phone):
#проходит до конца (или сразу добавляет в конец) и возвращает новую голову (если вставка в начало) или изменяет список по ссылке. Удобнее возвращать новую голову, если вставка может быть в начало.
if head is None:
return {'name': name, 'phone': phone, 'next': None}
current = head
while current is not None:
if current['name'] == name:
current['phone'] = phone
return head
if current['next'] is None:
current['next'] = {'name': name, 'phone': phone, 'next': None}
return head
current = current['next']
def ll_find(head, name):
# ищет узел, возвращает телефон или None.
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
def ll_list_all(head):
#собирает все записи в список и сортирует (сортировка вынесена отдельно).
result = []
current = head
while current is not None:
result.append((current['name'], current['phone']))
current = current['next']
result.sort(key=lambda x: x[0])
return result