代码如下:
#include"stdio.h"
#include"stdlib.h"
#include"string.h"
#define l sizeof(struct friends)
int i,n;char c,ch[20]={0};
struct friends
{
char name[20];
char phone[12];
struct friends*next;
};
struct friends *create()
{
struct friends *head;
struct friends *p1,*p2;
n=0;
p1=p2=(struct friends*)malloc(l);
do
{
printf("请依次输入每个联系人姓名、电话(空格间隔):");
scanf("%s,%s",&p2->name,&p2->phone);
if(n==0){head=p2;head->next=p1;}
else {p1=p2;p1->next=p2;}
p2=(struct friends*)malloc(l);
printf("是否继续输入,按y继续输入,其他键结束:");
scanf("%c",&c);
n++;
}while(c=='y');
p2->next=NULL;
return(head);
}
void print(struct friends *head)
{
for(i=0;i<n;i++)
{
printf("%s %s\n",head->name,head->phone);
head=head->next;
}
}
void search(struct friends *head)
{
printf("请输入要查找联系人姓名:\n");
scanf("%s",&ch);
for(i=0;i<n;i++)
{
if(head->name==ch){printf("该联系人的姓名: %s 电话: %s",head->name,head->phone);break;}
head=head->next;
}
}
void destory(struct friends *head)
{
struct friends *p;
while(head->next)
{
p=head;
head=head->next;
free(p);
}
}
int main()
{
struct friends *pt;
pt=create();
print(pt);
search(pt);
destory(pt);
}
预期结果如下:
实际输出如下:
不知道是哪里出了问题,希望有人能答疑解惑,非常感谢!