|
发表于 2018-9-8 10:58:21
|
显示全部楼层
你好 我在你的程序上做了修改 有些地方你写的不合理 我这只是个参考
注意 循环的时候一定要有结束条件
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define LEN sizeof(struct list)
struct list //定义链表
{
char *name;
long int num;
struct list *next;
};
int main(void)
{
struct list *p1,*p2,*head,*p;
printf("LEN = %d\n",LEN);
p1=p2=(struct list *)malloc(LEN); //申请第一个节点
printf("请输入姓名:");
scanf("%s",p1->name);
printf("请输入学号:");
scanf("%d",&p1->num);
head = NULL;
int n=0;
while(p1->num != 0) //动态申请节点并输入
{
n++;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct list *)malloc(LEN);
printf("请输入姓名:");
scanf("%s",p1->name);
printf("请输入学号:");
scanf("%d",&p1->num);
p2->next=p1;
p2=p1;
}
p2->next=NULL;
p2=head; //打印链表
while(p2->next)
{
printf("%d:姓名:%s 学号:%d\n",n+1,p2->name,p2->num);
p2=p2->next;
}
return 0;
}
|
|