forked from UNN/2026-rff_mp
[1] Implement linked list phonebook
This commit is contained in:
parent
154b9b8b65
commit
eb6587c537
67
KuznetsovYuM/docs/data/1-st-exercise/phonebook_structures.py
Normal file
67
KuznetsovYuM/docs/data/1-st-exercise/phonebook_structures.py
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
|
||||||
|
def linked_list_add(head, name, phone):
|
||||||
|
curr = head
|
||||||
|
while curr is not None:
|
||||||
|
if curr['name'] == name:
|
||||||
|
curr['phone'] = phone
|
||||||
|
return head
|
||||||
|
curr = curr['next']
|
||||||
|
|
||||||
|
new_node = {'name': name, 'phone': phone, 'next': None}
|
||||||
|
if head is None:
|
||||||
|
return new_node
|
||||||
|
|
||||||
|
curr = head
|
||||||
|
while curr['next'] is not None:
|
||||||
|
curr = curr['next']
|
||||||
|
curr['next'] = new_node
|
||||||
|
return head
|
||||||
|
|
||||||
|
|
||||||
|
def linked_list_find(head, name):
|
||||||
|
curr = head
|
||||||
|
while curr is not None:
|
||||||
|
if curr['name'] == name:
|
||||||
|
return curr['phone']
|
||||||
|
curr = curr['next']
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def linked_list_remove(head, name):
|
||||||
|
if head is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if head['name'] == name:
|
||||||
|
return head['next']
|
||||||
|
|
||||||
|
prev = head
|
||||||
|
curr = head['next']
|
||||||
|
while curr is not None:
|
||||||
|
if curr['name'] == name:
|
||||||
|
prev['next'] = curr['next']
|
||||||
|
return head
|
||||||
|
prev = curr
|
||||||
|
curr = curr['next']
|
||||||
|
return head
|
||||||
|
|
||||||
|
|
||||||
|
def linked_list_collect_all(head):
|
||||||
|
records = []
|
||||||
|
curr = head
|
||||||
|
while curr is not None:
|
||||||
|
records.append((curr['name'], curr['phone']))
|
||||||
|
curr = curr['next']
|
||||||
|
records.sort(key=lambda pair: pair[0])
|
||||||
|
return records
|
||||||
|
|
||||||
|
|
||||||
|
# Quick test
|
||||||
|
if __name__ == '__main__':
|
||||||
|
lst = None
|
||||||
|
lst = linked_list_add(lst, 'Alice', '111-222')
|
||||||
|
lst = linked_list_add(lst, 'Bob', '333-444')
|
||||||
|
lst = linked_list_add(lst, 'Alice', '555-666')
|
||||||
|
print(linked_list_find(lst, 'Alice')) # 555-666
|
||||||
|
print(linked_list_collect_all(lst)) # [('Alice','555-666'), ('Bob','333-444')]
|
||||||
|
lst = linked_list_remove(lst, 'Bob')
|
||||||
|
print(linked_list_collect_all(lst)) # [('Alice','555-666')]
|
||||||
Loading…
Reference in New Issue
Block a user