通讯录管理系统。(用单链表,C语言
时间: 2023-11-29 18:06:24 浏览: 49
好的,我可以为您介绍一下通讯录管理系统的实现。
通讯录管理系统可以用单链表来实现。单链表是一种常见的数据结构,它由一些节点组成,每个节点包含一个数据域和一个指向下一个节点的指针域。
在通讯录管理系统中,每个节点可以表示一个联系人的信息,包括姓名、电话号码、地址等。我们可以定义一个结构体来表示每个节点,例如:
```
typedef struct Contact {
char name[20];
char phone[20];
char address[50];
struct Contact *next;
} Contact;
```
其中,name、phone和address分别表示联系人的姓名、电话号码和地址,next是指向下一个节点的指针。
接下来,我们可以定义一些函数来实现通讯录管理系统的基本操作,例如:
1. 创建一个新的联系人节点
```
Contact *create_contact(char *name, char *phone, char *address) {
Contact *new_contact = (Contact *)malloc(sizeof(Contact));
strcpy(new_contact->name, name);
strcpy(new_contact->phone, phone);
strcpy(new_contact->address, address);
new_contact->next = NULL;
return new_contact;
}
```
2. 添加一个联系人节点到链表中
```
void add_contact(Contact **head, Contact *new_contact) {
if (*head == NULL) {
*head = new_contact;
} else {
Contact *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_contact;
}
}
```
3. 根据姓名查找联系人节点
```
Contact *find_contact(Contact *head, char *name) {
Contact *current = head;
while (current != NULL) {
if (strcmp(current->name, name) == 0) {
return current;
}
current = current->next;
}
return NULL;
}
```
4. 删除一个联系人节点
```
void delete_contact(Contact **head, char *name) {
Contact *current = *head;
Contact *previous = NULL;
while (current != NULL) {
if (strcmp(current->name, name) == 0) {
if (previous == NULL) {
*head = current->next;
} else {
previous->next = current->next;
}
free(current);
return;
}
previous = current;
current = current->next;
}
}
```
5. 显示所有联系人
```
void display_contacts(Contact *head) {
Contact *current = head;
while (current != NULL) {
printf("Name: %s\n", current->name);
printf("Phone: %s\n", current->phone);
printf("Address: %s\n", current->address);
printf("\n");
current = current->next;
}
}
```
通过调用这些函数,我们可以实现通讯录管理系统的基本功能。例如,我们可以先创建一些联系人节点,然后添加到链表中:
```
int main() {
Contact *head = NULL;
Contact *alice = create_contact("Alice", "123-456-7890", "123 Main St.");
Contact *bob = create_contact("Bob", "234-567-8901", "456 Oak Ave.");
Contact *charlie = create_contact("Charlie", "345-678-9012", "789 Pine Blvd.");
add_contact(&head, alice);
add_contact(&head, bob);
add_contact(&head, charlie);
display_contacts(head);
return 0;
}
```
输出结果为:
```
Name: Alice
Phone: 123-456-7890
Address: 123 Main St.
Name: Bob
Phone: 234-567-8901
Address: 456 Oak Ave.
Name: Charlie
Phone: 345-678-9012
Address: 789 Pine Blvd.
```
当然,这只是一个简单的例子,通讯录管理系统还可以根据具体需求进行扩展和优化。