&&&&&简单的链表问题&&&&&

来源:百度知道 编辑:UC知道 时间:2024/07/07 23:42:50
错在哪?为什么只能输入一次,第二次就出错。讲的详细追加20分。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct StuData{

int age;
struct StuData *next;
};

void main()
{
int i;
struct StuData *head;
struct StuData *last;
struct StuData *node;
struct StuData *temp;

head=NULL;

for(i=0;i<3;i++){

node= (struct StuData *)malloc(sizeof(struct StuData));
scanf("%d",&node->age);
if(head==NULL)
{
head = node;

}
else
{
last->next = node;
last = node;

}
printf("%d\n",node->age);
}
last->next=NULL;

temp=head;

if(temp==NULL)
{
printf("no");return;
}
while(temp!=NULL)
{
printf("\n%d",temp->age);
temp=temp->next;
}

因为你没有给last开空间
在node= (struct StuData *)malloc(sizeof(struct StuData)); 后面加一句
last=(struct StuData *)malloc(sizeof(struct StuData));就好了。

开始
node= (struct StuData *)malloc(sizeof(struct StuData));
scanf("%d",&node->age);
if(head==NULL)
{
head = node;

//这里是正确的。其次应该还要让他指向下一个节点的指针指空
node->next = null;
//再将指向最后一个节点的元素挂载到这个节点上
if(node->next==null)
last = node;
}
由于我用的这电脑没有装编译器 也不好帮你调试程序了
所以帮你指正一点东西也久这么多了希望对你有帮助