#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#include<Windows.h>
typedef struct person
{
char name[20];
int age;
char phone[12];
}person_t;
typedef struct node_
{
person_t psn;
struct node_t *next;
}node_t;
int menu(void)
{
printf("----------------------------------\n");
printf("-------欢迎使用通讯录系统---------\n");
printf("-------1.查找---------------------\n");
printf("-------2.添加---------------------\n");
printf("-------3.删除---------------------\n");
printf("-------4.显示---------------------\n");
printf("-------5.清空---------------------\n");
printf("-------0.退出---------------------\n");
printf("----------------------------------\n");
}
void Print(node_t *head)//打印通讯录
{
while (head != NULL)
{
printf("姓名:%s,年龄:%d,电话:%s\n", head->psn.name, head->psn.age, head->psn.phone);
head = head->next;
}
}
void search(node_t *head)//查找联系人
{
printf("请输入需要查找的联系人:");
char name[32];
scanf("%s", name);
node_t *cur = head;
while (cur != NULL)
{
if (strcmp(name, cur->psn.name) == 0)
{
printf("姓名:%s,年龄:%d,电话:%s", cur->psn.name, cur->psn.age, cur->psn.phone);
break;
}
cur = cur->next;
}
if (cur == NULL)
{
printf("查无此人\n");
}
}
void insert(node_t **head)//增加联系人
{
node_t *p = malloc(sizeof(node_t));
p->next = NULL;
printf("请输入姓名:>");
scanf("%s", p->psn.name);
printf("请输入年龄:>");
scanf("%d", &p->psn.age);//&p
printf("请输入电话:>");
scanf("%s", p->psn.phone);
p->next = *head;//
*head = p;//
Print(*head);
}
void errse(node_t **head)//删除联系人
{
printf("请输入需要删除的联系人:");
char name[32];
scanf("%s", name);
node_t *cur = *head;
node_t *pre = NULL;
while (cur != NULL)
{
if (strcmp(name, cur->psn.name) == 0)
{
if (pre != NULL)
{
pre->next = cur->next;
}
else
{
*head = cur->next;
}
free(cur);
break;
}
pre = cur;
cur = cur->next;
}
Print(*head);
}
void show(node_t *head)//显示联系人
{
printf("通讯录中的联系人有:>");
while (head != NULL)
{
printf("%s ", head->psn.name);
head = head->next;
}
}
void empty(node_t **head)//清空联系人
{
node_t *cur = *head;
while (cur != NULL)
{
cur = cur->next;
}
*head = cur;
printf("清空完毕\n");
}
int main()
{
int i = 0;
node_t *head = NULL;
while (1)
{
menu();
printf("请选择:\n");
scanf("%d", &i);
switch (i)
{
case 1:
search(head);
break;
case 2:
insert(&head);
break;
case 3:
errse(&head);
break;
case 4:
show(head);
break;
case 5:
empty(&head);
break;
case 0:
printf("Quit.>\n");
break;
default:
printf("按键错误,请重新选择\n");
break;
}
}
if (head == NULL)
{
printf("ok\n");
}
system("pause");
return 0;
}
该通讯录实现了查找、增加、删除、显示、清空联系人这五项功能。