33,311
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct grade
{
int s;
struct grade*next
} n;
n*creat(void)
{
n*head,*node,*end;
head=NULL;
while(1)
{
node=(n*)malloc(sizeof(n));
node->next=NULL;
scanf("%d", &node->s);
printf("&");
if (head == NULL) {
head = node;
end = node;
}
else
end->next=node;
node->next=NULL;
end=node;
if(node->s==0)
{ end->next=NULL;
break;
}
}
return(head);
}
void main()
{
n*p;
p=creat();
while(p->next!=NULL)
{
printf("%d",p->s);
p=p->next;
}
}
你的代码基础上改的,大致三个问题:
1. scanf输入的是指针
2. 你的代码没有对第一次进入循环进行判断,第一次进循环head是空指针直接挂了
3. main函数打印的地方应该先打印,不然打不出头指针的值#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct grade
{
int s;
struct grade *next;
} n;
n*creat(void)
{
n*head,*node,*end;
head=NULL;
while(1)
{
node=(n*)malloc(sizeof(n));
node->next = NULL;
scanf("%d", &node->s);
if (node->s == 0) {
free(node);
break;
}
//printf("&");
if (head == NULL) {
head = node;
end = node;
} else {
end->next = node;
end = node;
}
/*
//node->next=NULL;
if(node->s==0)
{ end->next=NULL;
break;
}
*/
}
return(head);
}
//void main()
int main()
{
n*p;
p=creat();
//while(p->next!=NULL)
while(p)
{
printf("%d",p->s);
p=p->next;
}
return 0;
}