关于链表输出问题
程序代码:#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode *next;
};
struct ListNode *readlist();
void printlist( struct ListNode *L )
{
struct ListNode *p = L;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
int m;
struct ListNode *L = readlist();
printlist(L);
return 0;
}
struct ListNode *readlist()
{
int a,i=0;
struct ListNode *L,*p,*r;
r=(struct ListNode *)malloc(sizeof(struct ListNode));
p=r;
scanf("%d",&a);
while(a!=-1)
{
i++;
if(i==1)
{
L=r;
r->data=a;
p=r;
r->next=NULL;
}
else
{
r->data=a;
p->next=r;
p=r;
r->next=NULL;
}
r=(struct ListNode *)malloc(sizeof(struct ListNode));
scanf("%d",&a);
}
//我把while里面的两行“r->next=NULL”放在这一行输出怎么会出错呢?错误是输入的数字有的但后面全是垃圾值
return L;
}








