c语言建立和输出单链表程序中,为什么第一个数据没输出来?请各位高手帮忙看看,不胜感激!!!
#include<stdio.h>#include<malloc.h>#defineNULL0structstudent{intdate;structstudent*ne...
#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<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;
}
} 展开
2个回答
展开全部
楼主你好,你的代码问题出了一点小问题:
#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)); //此处重新开辟了新空间,len==0时,会导致之前的head指向的是新开辟的空间,而不是之前那个存放数据的空间。
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\n",p->date);
p=p->next;
}
}
#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)); //此处重新开辟了新空间,len==0时,会导致之前的head指向的是新开辟的空间,而不是之前那个存放数据的空间。
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\n",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;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询