95 lines
2.7 KiB
Python
95 lines
2.7 KiB
Python
def ll_insert(head, name, phone):
|
||
|
||
"""
|
||
проходит до конца (или сразу добавляет в конец)
|
||
возвращает новую голову (если вставка в начало) или изменяет список по ссылке.
|
||
"""
|
||
new_node = {'name': name, 'phone': phone, 'next': None}
|
||
|
||
# в случае пустого списка, новый узел становится головой
|
||
if head is None:
|
||
return new_node
|
||
|
||
# в противном случае проходим в конец списка
|
||
current = head
|
||
while current['next'] is not None:
|
||
if current['name'] == name:
|
||
current['phone'] = phone
|
||
return head
|
||
current = current['next']
|
||
|
||
# проверяем последний узел
|
||
if current['name'] == name:
|
||
current['phone'] = phone
|
||
else:
|
||
current['next'] = new_node
|
||
|
||
return head
|
||
|
||
|
||
|
||
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:
|
||
new_head = head['next']
|
||
head['next'] = None
|
||
return new_head
|
||
|
||
# ищем узел для удаления
|
||
current = head
|
||
while current['next'] is not None:
|
||
if current['next']['name'] == name:
|
||
target = current['next']
|
||
current['next'] = target['next']
|
||
target['next'] = None # разрываем связь у удаляемого узла (иными словами, обнуление ссылки)
|
||
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']
|
||
|
||
# ручная сортировка пузырьком
|
||
n = len(result)
|
||
for i in range(n):
|
||
for j in range(0, n - i - 1):
|
||
if result[j][0] > result[j + 1][0]:
|
||
result[j], result[j + 1] = result[j + 1], result[j]
|
||
|
||
return result |