微信多开器ios:链表输入没问题,但是打印时却只能显示第一个node的内容??help me

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/03 07:43:36
#include<stdio.h>
#include<alloc.h>
#define len sizeof(student)
typedef struct stu{
char name[6];
int age;
struct stu *next;
}student;

student *create(){
student *head=NULL,*p1,*p2;
int n=0;
/****************for()-----------start*/
for(;;){
p2=p1=(student *)malloc(len);
printf("input your name:\n");
scanf("%s",p1->name);
if(p1->name[0]=='o')break;
printf("input your age:\n");
scanf("%d",&p1->age);
n++;
if(n==1) head=p1;
else p1=p2->next;
p2=p1;
}
/***************for()-------------end*/
p2->next=NULL;
return(head);
}

void print(student *head){
student *p;
int n=0;
p=head;
while(p!=NULL){
printf("name:%s\n",p->name);
printf("age :%d\n",p->age);
printf("%d\n",++n);
//p->next=p;
p=p->next;
printf("test\n");
}
}

void main(void){
student *head;
head=create();
print(head);
}

调试了半个小时 终于找出错来拉
student *create(){
student *head,*p1,*p2;
int n=1;
p1=p2=(student *)malloc(len);
for(;;){
printf("input your name:\n");
scanf("%s",p1->name);
if(p1->name[0]=='o')break;
printf("input your age:\n");
scanf("%d",&p1->age);
if(n==1)
head=p1;
p1=(student *)malloc(len);
p1=p2->next;
p2=p1;
n++;}
/***************for()-------------end*/
p1->next=NULL;
return(head);
}

student *create(){
student *head=NULL,*p1,*p2;
int n=0;
/****************for()-----------start*/
for(;;){
p2=p1=(student *)malloc(len);
//这句不对。p2 = (student *)malloc(len);

printf("input your name:\n");
scanf("%s",p1->name);
if(p1->name[0]=='o')break;
printf("input your age:\n");
scanf("%d",&p1->age);
n++;
if(n==1) head=p1; //这句也要改 head = p2;
else p1=p2->next; //这句话写错了,p1->next = p2;
p2=p1; //同时这一句也不对, p1 = p2;
}
/***************for()-------------end*/
p2->next=NULL;
return(head);
}