C语言简单链表问题

# include <stdio.h>
# include <malloc.h>
struct list
{ int data;
struct list *next;
};
typedef struct list node;
main()
{ node *head,*r;
int num,i;
r=(node *)malloc(sizeof(node));
r=head;
for(i=0;i<3;i++)
{ scanf("%d",&num);
r->data=num;
r->next=(node *)malloc(sizeof(node));
r=r->next;
}
r->next=NULL;
r=head;
while(r->next!=NULL)
{ printf("%d",r->data);
r=r->next;
}
}
这是为什么呢,请高手细心讲解下。谢谢

#include <stdio.h>
#include <malloc.h>
struct list
{
int data;
struct list *next;
};
typedef struct list node;
main()
{
node *head,*r;
int num,i;
r=(node *)malloc(sizeof(node));
head = r; //这里head赋值为r,下面r再赋值回来,遍历
for(i=0;i<3;i++)
{
scanf("%d",&num);
r->data=num;
r->next=(node *)malloc(sizeof(node));
r=r->next;
}
r->next=NULL;
r=head;
while(r->next!=NULL)
{
printf("%d",r->data);
r=r->next;
}
}

追问

原理是什么呢。麻烦讲解下。谢谢

追答

就是用head保存头指针啊。如果是:
r=(node *)malloc(sizeof(node));
r=head;
的话,head都没有初始化,那r的值就没有意义,下面怎么能r->data=num;这样使用呢

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-09-01
r=(node *)malloc(sizeof(node));
r=head;

你知道这边做了什麼事吗?

向系统索取记忆体, 又把他丢了. 让r = head, 而head, 根本没有内容.
head =(node *)malloc(sizeof(node));
r=head;
比较像是你要的.
相似回答