链表输出问题
# include "stdio.h"
struct student
{
char num;
struct student *list;
};
struct student *in()
{
struct student *h,*p1,*p2;
char a;
p1=(struct student*)malloc(sizeof(struct student));
printf("please input interger\n");
while(a!='!')
{scanf("%s",&a);
p1->num=a;
if(h==NULL)
{h=p1;p2=p1;}
else{p2->list=p1;p2=p1;}
}p2->list=NULL;
return h;
}
main ()
{struct student *l;
l=in();while(l)
{printf ("sdfsdf");
printf("%s",l->num);l=l->list;}getch();
}
[解决办法]
建议楼主对变量定义时初始化,尤其是函数中的char a,还有这格式,看程序时很不舒服。
在函数中p1=(struct student*)malloc(sizeof(struct student));
申请的内存用p1指向,申请了一次,后边又把结构体里的指针指向这个空间,也就是就一个变量反复赋值。
楼主只粘贴程序上来有没有文字,不知道什么意思,按我理解可以试试吧
p1=(struct student*)malloc(sizeof(struct student));
放到while循环里,这样每次都新申请空间存放字符a的值。
[解决办法]
代码错误百出,建议网上搜一下“单链表的创建”,看一下别人的代码怎么写的。
[解决办法]
很多错误,我帮你改了一下:
#include <stdio.h>#include <stdlib.h> //Used for Allocate memorystruct student{ char num; struct student *list;};struct student * in(){ struct student *h=NULL,*p1=NULL,*p2=NULL; //为防止野指针,声明指针时赋值为NULL char a; printf("please input interger:\n"); //我想你的意思是!不包括在链表中吧 while(1) { scanf("%c",&a); if (a=='!') { break; } p1=(struct student*)malloc(sizeof(struct student));//每次都重新创建一个结点了,所以要重新分配内存 p1->num=a; if(h==NULL) { h=p1;p2=p1; } else { p2->list=p1;p2=p1; } getchar(); } p2->list=NULL; return h;}main (){ struct student *l; l=in(); while(l) { /*printf ("sdfsdf");*/ printf("%5c",l->num); l=l->list; } printf("\n"); getch();}