链表输出问题

来源:百度知道 编辑:UC知道 时间:2024/06/05 12:57:05
#include<stdio.h>
#include<malloc.h>
#include <stdlib.h>
struct list
{
int num;
list *next;
};

typedef list List;
typedef list* pList;

int main()
{

pList head,p,q;
head=(pList)malloc(sizeof(List));
p=head;
for (int i=1;i<10;i++)
{
p->num=i;
q=(pList)malloc(sizeof(List));
p->next=q;
p=q;
}
p->next=NULL;

p=head;
while (p!=NULL)
{
printf("%d\n",p->num );
p=p->next;
}

system("pause");
return 0;
}

最后一行有个随机值 哪里写错了呢?

下面是改后的:
#include<stdio.h>
#include<malloc.h>
#include <stdlib.h>
struct list
{
int num;
list *next;
};

typedef list List;
typedef list* pList;

int main()
{

pList head,p,q;
head=(pList)malloc(sizeof(List));
p=head;
for (int i=1;i<10;i++)
{
p->num=i;
q=(pList)malloc(sizeof(List));
p->next=q;
p=q;
}
p->num=10;
p->next=NULL;

p=head;
while (p!=NULL)
{
printf("%d\n",p->num );
p=p->next;
}

system("pause");
return 0;
}
for循环倒i=10时,条件不成立,退出循环,这样最后一个结点中的值不是10而是一个随机数,所以出现错误

这样的问题最好分析了。
将循环改成极端情况,就懂了,改与下面这样:
for (int i=1;i<1;i++)
{...}

那么,循环就一次也不运行,但结果是输出一个随机数。

^_^

因为你的head已经在循环开始前就生成了一个结点了,然后循环开始后,每次循环又生成了一个结点,最后一次循环生成的那个结点是废的