#include<stdio.h>
#include<malloc.h>
#define NULL 0
struct student
{int date;
struct student *next;
};
void main()
{struct student *head,*p,*r;
int i,j,len=0;
p=(struct student *)malloc(sizeof(struct student));
printf("input the date:");
scanf("%d",&p->date);
while(p->date!=0)
{p=(struct student *)malloc(sizeof(struct student));
if(len==0)
{head=r=p;len++;}
else
{r->next=p;
r=p;len++;}
scanf("%d",&p->date);
}free(p);
p->next=NULL;
p=head;
while(p->next!=NULL)
{printf("%d",p->date);
p=p->next;
}
}
那应该怎么改呢?我是在自学,感觉最基本的问题都不好领会啊
追答我建议使用一个变量用来接收判断的数据,满足条件后再存入链表。
#include
#include
#define NULL 0
struct student
{int date;
struct student *next;
};
void main()
{
struct student *head,*p,*r;
int i,j,len=0,num;
printf("input the date:");
scanf("%d",&num);
while(num!=0)
{
p=(struct student *)malloc(sizeof(struct student));
p->date=num;
if(len==0)
{
head=r=p;
len++;}
else
{
r->next=p;
r=p;
len++;
}
scanf("%d",&num);
}
//此处如果用free(p),会切断指针和相应节点的关联,从而使后面的p->next=NULL;没有意义。
p->next=NULL;
p=head;
while(p!=NULL)
{
printf("%d\n",p->date);
p=p->next;
}
}