帮忙看下这个链表程序什么问题

来源:百度知道 编辑:UC知道 时间:2024/05/24 14:54:26
代码如下:
#include <iostream>

using namespace std;

struct chain
{
int no;
chain *next;
};

chain* create()
{
chain *head,*p;
int i=1;
for (int j=0;j<5;j++)
{
p=(chain*)malloc(sizeof(chain));
if(p==0)
{
printf("out of memory!");
}
if(j==0)
{
head=p;
}
p->no=i;

p=p->next;
i+=2;
}
p=NULL;
return head;
}

void shownode(chain *head)
{
while(head!=0)
{
printf("%d",head->no);
head=head->next;
}
}

void main()
{
chain *q;
q=create();
shownode(q);
}

用VC跟踪发现在shownode中,head->next根本就指的不对了,如果说是作用域的原因?那为什么1可以打印出来呢?不明白,请教;

p=(chain*)malloc(sizeof(chain));

p=p->next;
新添加的点根本没有连接到链表中 阿;

修改>>

chain* create()
{
chain *head,*p,*q;
int i=1;
for (int j=0;j<5;j++)
{
p=(chain*)malloc(sizeof(chain));
if(p==0)
{
printf("out of memory!");
}
if(j==0)
{
head=p;
q=p;
}
else
{
q->next = p;
q=p;
}
p->no=i;

i+=2;
}
q->next = NULL;
return head;
}