forked from UNN/2026-rff_mp
[1] start 1-st-exercise
This commit is contained in:
parent
dd03fdd059
commit
c967240036
67
BoriskovaDV/docs/data/1-st-exercise/linked_list_phonebook.py
Normal file
67
BoriskovaDV/docs/data/1-st-exercise/linked_list_phonebook.py
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
def create_node(name, phone):
|
||||||
|
return {'name': name, 'phone': phone, 'next': None}
|
||||||
|
|
||||||
|
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 = create_node(name, phone)
|
||||||
|
|
||||||
|
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 pair: pair[0])
|
||||||
|
return records
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
head = None
|
||||||
|
head = ll_insert(head, 'Иван', '123-456')
|
||||||
|
head = ll_insert(head, 'Борис', '789-012')
|
||||||
|
head = ll_insert(head, 'Анна', '345-678')
|
||||||
|
head = ll_insert(head, 'Иван', '111-222')
|
||||||
|
print(ll_list_all(head))
|
||||||
|
print(ll_find(head, 'Иван'))
|
||||||
|
print(ll_find(head, 'Петр'))
|
||||||
|
head = ll_delete(head, 'Борис')
|
||||||
|
print(ll_list_all(head))
|
||||||
Loading…
Reference in New Issue
Block a user