写一串单链表通讯录管理系统的数据结构代码
时间: 2023-07-21 12:28:45 浏览: 54
好的,以下是一个简单的单链表通讯录管理系统的数据结构代码示例,供您参考:
```python
class Contact:
def __init__(self, name, phone_number):
self.name = name
self.phone_number = phone_number
self.next = None
class ContactBook:
def __init__(self):
self.head = None
def add_contact(self, name, phone_number):
new_contact = Contact(name, phone_number)
if not self.head:
self.head = new_contact
else:
current_contact = self.head
while current_contact.next:
current_contact = current_contact.next
current_contact.next = new_contact
def delete_contact(self, name):
if not self.head:
print("Contact book is empty.")
elif self.head.name == name:
self.head = self.head.next
else:
current_contact = self.head
while current_contact.next and current_contact.next.name != name:
current_contact = current_contact.next
if not current_contact.next:
print(f"{name} not found in contact book.")
else:
current_contact.next = current_contact.next.next
def search_contact(self, name):
if not self.head:
print("Contact book is empty.")
else:
current_contact = self.head
while current_contact and current_contact.name != name:
current_contact = current_contact.next
if not current_contact:
print(f"{name} not found in contact book.")
else:
print(f"Name: {current_contact.name} Phone number: {current_contact.phone_number}")
def display_contacts(self):
if not self.head:
print("Contact book is empty.")
else:
current_contact = self.head
while current_contact:
print(f"Name: {current_contact.name} Phone number: {current_contact.phone_number}")
current_contact = current_contact.next
```
这个数据结构包括两个类,`Contact` 和 `ContactBook`, `Contact` 类代表一个联系人,包含名字、电话号码和下一个联系人的指针;`ContactBook` 类代表整个通讯录,包含一个指向第一个联系人的头指针,以及添加、删除、查找和显示联系人等操作的方法。
希望这个示例代码可以帮助到您!