|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
初学链表,刚刚才弄懂书上的例题,合起书自己写了下代码,要求是:创建一个链表,该链表可以存放任意长度的名字,输入0表示结束输入.
但是我输入0发现跟本结束不了,求解.自己调试发现p2->name输入之后还是空的,所以while判断不起作用,是什么原因我找不出来,求解!
代码:
- #include<stdio.h>
- #include<malloc.h>
- #define NULL 0
- #define LEN sizeof(struct student)
- struct student
- {
- char *name;
- struct student *student_next;
- };
- struct student *creat(struct student *h);
- void print_student(struct student *h);
- void main()
- {
- struct student *head;
- head=NULL;
- printf("请输入学生的名字,以输入零结束输入:\n");
- head=creat(head);
- print_student(head);
- }
- struct student *creat(struct student *h)
- {
- struct student *p1,*p2;
- p1=p2=(struct student *)malloc(LEN);
- if(p2!=NULL)
- {
- scanf("%c",&p2->name);
- p2->student_next=NULL;
- }
- while(p2->name!='0')
- {
- if(h==NULL)
- {
- h=p2;
- }
- else
- {
- p1->student_next=p2;
- }
- p1=p2;
- p2=(struct student *)malloc(LEN);
- if(p2!=NULL)
- {
- scanf("%c",&p2->name);
- p2->student_next=NULL;
- }
- }
- return h;
- }
- void print_student(struct student *h)
- {
- struct student *temp;
- temp=h;
- while(temp)
- {
- printf("%c ",temp->name);
- temp=temp->student_next;
- }
- }
复制代码
|
|