使用链表实现通讯录是一种常见的方法,因为链表能够方便地插入和删除联系人信息。以下是一个简单的使用链表实现通讯录的步骤和示例代码:
步骤:
1. 定义链表节点:每个节点包含联系人的信息,如姓名、电话号码等。
2. 创建链表:初始化一个空链表。
3. 添加联系人:向链表中添加新的联系人节点。
4. 查找联系人:根据姓名或电话号码查找联系人。
5. 删除联系人:根据姓名或电话号码删除联系人。
6. 遍历链表:遍历链表以显示所有联系人信息。
示例代码(Python):
```python
class ContactNode:
def __init__(self, name, phone):
self.name = name
self.phone = phone
self.next = None
class ContactList:
def __init__(self):
self.head = None
def add_contact(self, name, phone):
new_node = ContactNode(name, phone)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def find_contact(self, name):
current = self.head
while current:
if current.name == name:
return current
current = current.next
return None
def delete_contact(self, name):
current = self.head
previous = None
while current:
if current.name == name:
if previous:
previous.next = current.next
else:
self.head = current.next
return True
previous = current
current = current.next
return False
def display_contacts(self):
current = self.head
while current:
print(f"Name: {current.name