我编写了一个通讯录,程序如下。现在的问题是节点控制n是由r来控制的。r就是这个通讯录中人员的个数。如图所示。如果规定通讯录中有三条记录的话,循环就会执行三次,再加上前边输的一次就会输入四条记录。但如果改为r-1的话,是输入了三条记录,可输出的时候即只有两条了。因为n现在等于2。
请高手帮帮忙,解答一下啊!
源程序(只包含了建立和输出链表):
#define NULL 0
#define LEN sizeof(struct address)
#define LINE "%s%ld%ld%s%ld%ld%s"
#include <stdlib.h>
/*定义结构体*/
struct address
{
char name[10];
long number;
long mobliephone;
char address[100];
long QQ_number;
long MSN_number;
char e_mail[50];
struct address *next;
};
int n;/*全局变量*/
/*链表的建立*/
struct address *creat(void)
{
struct address *head;
struct address *member1,*member2;
int r;
n=0;
printf("How many people in the address?\n");
scanf("%d",&r);
member1=member2=(struct address *)malloc(LEN);
printf("\nplease input name number mp add qq msn email\n");
scanf(LINE,member1->name,&member1->number,&member1->mobliephone,member1->address,&member1->QQ_number,&member1->MSN_number,member1->e_mail);
head=NULL;
n=0;
while(n<r)
{
n=n+1;
if(n==1) head=member1;
else member2->next=member1;
member2=member1;
member1=(struct address *)malloc(LEN);
printf("Please input new records again.");
scanf(LINE,member1->name,&member1->number,&member1->mobliephone,member1->address,&member1->QQ_number,&member1->MSN_number,member1->e_mail);
}
member2->next=NULL;
return (head);
}
/*输出函数*/
void print(struct address *head)
{ struct address *p;
printf("\n Now,these %d records are:\n",n);
printf("\nname number mobilephone address QQ MSN E_mail\n");
p=head;
if(head!=NULL)
do
{printf("%s %ld %ld %s %ld %ld %s\n",p->name,p->number,p->mobliephone,p->address,p->QQ_number,p->MSN_number,p->e_mail);
p=p->next;
}while(p!=NULL);
}
main()
{
struct address *head;
head=creat();
print(head);
printf("\n");
}