利用单链表实现电话本的模拟程序定义单链表的数据类型将头插法和尾插法插入删除查找修改技术拟制输出等操作都定义成此函数的形式最后在主函数中调用它并将每一种操作前后的结果输出以查看每一种操作最后的结果完整代码 c语言
时间: 2024-06-04 18:14:00 浏览: 68
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义电话本结构体
typedef struct phonebook {
char name[20];
char phone[11];
struct phonebook *next;
} PhoneBook;
// 头插法插入电话本信息
PhoneBook *insertHead(PhoneBook *head) {
PhoneBook *p = (PhoneBook*)malloc(sizeof(PhoneBook));
printf("请输入姓名:");
scanf("%s", p->name);
printf("请输入电话:");
scanf("%s", p->phone);
p->next = head;
head = p;
printf("添加成功!\n");
return head;
}
// 尾插法插入电话本信息
PhoneBook *insertTail(PhoneBook *head) {
PhoneBook *p = (PhoneBook*)malloc(sizeof(PhoneBook));
printf("请输入姓名:");
scanf("%s", p->name);
printf("请输入电话:");
scanf("%s", p->phone);
p->next = NULL;
if (head == NULL) {
head = p;
} else {
PhoneBook *q = head;
while (q->next != NULL) {
q = q->next;
}
q->next = p;
}
printf("添加成功!\n");
return head;
}
// 根据姓名查找电话本信息
void searchByName(PhoneBook *head) {
printf("请输入要查找的姓名:");
char name[20];
scanf("%s", name);
PhoneBook *p = head;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
printf("姓名:%s,电话:%s\n", p->name, p->phone);
return;
}
p = p->next;
}
printf("未找到该用户!\n");
}
// 根据电话查找电话本信息
void searchByPhone(PhoneBook *head) {
printf("请输入要查找的电话:");
char phone[11];
scanf("%s", phone);
PhoneBook *p = head;
while (p != NULL) {
if (strcmp(p->phone, phone) == 0) {
printf("姓名:%s,电话:%s\n", p->name, p->phone);
return;
}
p = p->next;
}
printf("未找到该用户!\n");
}
// 修改电话本信息
void modify(PhoneBook *head) {
printf("请输入要修改的姓名:");
char name[20];
scanf("%s", name);
PhoneBook *p = head;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
printf("请输入新的电话:");
scanf("%s", p->phone);
printf("修改成功!\n");
return;
}
p = p->next;
}
printf("未找到该用户!\n");
}
// 删除电话本信息
PhoneBook *delete(PhoneBook *head) {
printf("请输入要删除的姓名:");
char name[20];
scanf("%s", name);
PhoneBook *p = head;
PhoneBook *pre = NULL;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
if (pre == NULL) {
head = p->next;
} else {
pre->next = p->next;
}
free(p);
printf("删除成功!\n");
return head;
}
pre = p;
p = p->next;
}
printf("未找到该用户!\n");
return head;
}
// 输出电话本信息
void print(PhoneBook *head) {
PhoneBook *p = head;
while (p != NULL) {
printf("姓名:%s,电话:%s\n", p->name, p->phone);
p = p->next;
}
}
int main() {
PhoneBook *head = NULL;
int choice;
do {
printf("1.头插法插入电话本信息\n2.尾插法插入电话本信息\n3.根据姓名查找电话本信息\n4.根据电话查找电话本信息\n5.修改电话本信息\n6.删除电话本信息\n7.输出电话本信息\n8.退出\n");
printf("请输入操作编号:");
scanf("%d", &choice);
switch(choice) {
case 1:
head = insertHead(head);
break;
case 2:
head = insertTail(head);
break;
case 3:
searchByName(head);
break;
case 4:
searchByPhone(head);
break;
case 5:
modify(head);
break;
case 6:
head = delete(head);
break;
case 7:
print(head);
break;
case 8:
printf("程序结束!");
break;
default:
printf("请输入正确的操作编号!\n");
}
} while (choice != 8);
return 0;
}
阅读全文