使用线性表实现通讯录的建立的代码
时间: 2023-05-19 16:03:48 浏览: 76
以下是使用线性表实现通讯录的建立的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define MAX_PHONE_LEN 11
#define MAX_CONTACTS 100
typedef struct {
char name[MAX_NAME_LEN];
char phone[MAX_PHONE_LEN];
} Contact;
typedef struct {
Contact contacts[MAX_CONTACTS];
int count;
} ContactList;
void addContact(ContactList *list, Contact contact) {
if (list->count >= MAX_CONTACTS) {
printf("通讯录已满,无法添加新联系人!\n");
return;
}
list->contacts[list->count] = contact;
list->count++;
printf("添加联系人成功!\n");
}
void deleteContact(ContactList *list, char *name) {
int i, j;
for (i = 0; i < list->count; i++) {
if (strcmp(list->contacts[i].name, name) == 0) {
for (j = i; j < list->count - 1; j++) {
list->contacts[j] = list->contacts[j + 1];
}
list->count--;
printf("删除联系人成功!\n");
return;
}
}
printf("未找到该联系人!\n");
}
void searchContact(ContactList *list, char *name) {
int i;
for (i = 0; i < list->count; i++) {
if (strcmp(list->contacts[i].name, name) == 0) {
printf("联系人姓名:%s,电话号码:%s\n", list->contacts[i].name, list->contacts[i].phone);
return;
}
}
printf("未找到该联系人!\n");
}
void printContacts(ContactList *list) {
int i;
printf("通讯录中共有 %d 个联系人:\n", list->count);
for (i = 0; i < list->count; i++) {
printf("联系人姓名:%s,电话号码:%s\n", list->contacts[i].name, list->contacts[i].phone);
}
}
int main() {
ContactList list = {0};
int choice;
char name[MAX_NAME_LEN], phone[MAX_PHONE_LEN];
Contact contact;
while (1) {
printf("请选择操作:\n");
printf("1. 添加联系人\n");
printf("2. 删除联系人\n");
printf("3. 查找联系人\n");
printf("4. 显示所有联系人\n");
printf("5. 退出程序\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("请输入联系人姓名:");
scanf("%s", name);
printf("请输入联系人电话号码:");
scanf("%s", phone);
strcpy(contact.name, name);
strcpy(contact.phone, phone);
addContact(&list, contact);
break;
case 2:
printf("请输入要删除的联系人姓名:");
scanf("%s", name);
deleteContact(&list, name);
break;
case 3:
printf("请输入要查找的联系人姓名:");
scanf("%s", name);
searchContact(&list, name);
break;
case 4:
printContacts(&list);
break;
case 5:
printf("程序已退出!\n");
exit(0);
default:
printf("无效的选择!\n");
break;
}
}
return 0;
}
阅读全文