小甲鱼C语言单链表通讯录作业
写完之后并没有找到答案,调试了几次并没有出现错误,可以给没有写出来的朋友参考参考,如果代码有什么错误,或者不足欢迎指出,一起进步。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person
{
char name[20];
char phonenumber[13];
struct person *next;
}
getInput(struct person *person)//为新struct赋值
{
fflush(stdout);
printf("请输入联系人姓名:");
scanf("%s",person->name);
printf("请输入联系人电话:");
fflush(stdout);
scanf("%s",person->phonenumber);
}
addPerson(struct person **head)//添加新的联系人
{
struct person *person,*temp;
person=(struct person *)malloc(sizeof(struct person));
if(person==NULL)
{
printf("内存分配失败!");
exit(1);
}
getInput(person);
if(*head==NULL)
{
*head=person;
person->next=NULL;
}else{
temp=*head;
*head=person;
person->next=temp;
}
}
struct person *findPerson(struct person *head,char name[20])//查找已有联系人
{
struct person *temp;
temp=head;
while(strcmp(name,temp->name)!=0)
{
temp=temp->next;
if(temp==NULL)
{
break;
}
}
return temp;
}
putoutPerson(struct person *temp)//输出指定联系人
{
if(temp==NULL)
{
printf("未查询到您输入的姓名\n");
}else{
printf("姓名:%s\n",temp->name);
printf("电话:%s\n",temp->phonenumber);
}
}
changePerson(struct person *head)//更改已有联系人
{
char name[20];int pattern=0;
struct person *person;
printf("请输入你要更改的联系人姓名:");
do
{
scanf("%s",name);
person=findPerson(head,name);
if(person==NULL)
{
printf("未找到要求修改的联系人,请重新输入:");
}
}while(person==NULL);
printf("请输入您要更改内容的序号 1.姓名 2.电话\n");
LOOP: scanf("%d",&pattern);
if(pattern==1)
{
printf("已选定修改姓名,请输入:");
scanf("%s",person->name);
}else if(pattern==2)
{
printf("已选定修改电话,请输入:");
scanf("%s",person->phonenumber);
}else{
printf("更改内容失败,请输入正确序号\n");
goto LOOP;
}
printf("修改成功!\n");
}
delPerson(struct person **head)//删除已有联系人
{
char name[20];struct person *temp,*tempbefore;
temp=*head;
tempbefore=NULL;
printf("请输入要删除的联系人姓名:");
scanf("%s",name);
while(temp!=NULL && strcmp(temp->name,name)!=0)
{
tempbefore=temp;
temp=temp->next;
}if(temp==NULL)
{
printf("未查询到您输入的姓名");
return;
}else
{
if(tempbefore == NULL)
{
*head=temp->next;
}else{
tempbefore->next=temp->next;
}
free(temp);
}
}
displayContacts(struct person *head)//显示当前联系人
{
struct person *temp;
temp=head;
while(temp!=NULL)
{
printf("\n姓名:%s\n",temp->name);
printf("电话:%s\n",temp->phonenumber);
temp=temp->next;
}
}
release(struct person **head)
{
struct person *temp;
while(*head!=NULL)
{
temp=*head;
*head=(*head)->next;
free(temp);
}
}
int main(int argc, char *argv[])
{
int option=0;struct person *head=NULL;
char name[20];
while(option!=6)
{
printf("\n1.插入新的联系人 2.查找已有联系人\n");
printf("3.更改已有联系人 4.删除已有联系人\n");
printf("5.显示当前通讯录 6.退出通讯录程序\n");
printf("请输入你要进行的操作序号:");
scanf("%d",&option);
if(option==6)
{
return;
}else if(option==1){
addPerson(&head);
}else if(option==5){
displayContacts(head);
}else if(option==2){
printf("请输入要查询的联系人姓名:");
scanf("%s",name);
putoutPerson(findPerson(head,name));
}else if(option==3){
changePerson(head);
}else if(option==4){
delPerson(&head);
}
}
release(head);
}