读书人

初学者询问链表的输出有关问题

发布时间: 2012-06-17 21:02:01 作者: rapoo

菜鸟询问链表的输出问题
程序实现的功能很简单,就是创建一个链表,然后输出这个链表的全部数据的值
程序的代码是这样的:


#include<iostream.h>
struct Node{
int num;
Node *next;
};
Node *Creat()
{
int n=0;
Node * p1,*p2,*head;
head=NULL;
p1=new Node;
p2=new Node;
cout<<"input a num"<<endl;
cin>>p1->num;
while(p1->num!=0)
{
p1->next=p2;
if(n==0)
{
head=p1;
}
p2=p1;
p1=new Node;
cout<<"input a num"<<endl;
cin>>p1->num;
p1->next=NULL;
}
return head;
}
void Print(Node *a)
{
Node *p=a;
while(p)
{
cout<<p->num<<endl;
p=p->next;
}
}
main()
{
Node *a;
//
a=new Node;
a=Creat();
Print(a);
}



按照以下输入:
input a num
3
input a num
2
input a num
1
input a num
0

输出为:
1
2
3
-842150451
Press any key to continue


最后一个数怎么会是一个越界的数字呢...纠结得不到其解,求哪位好心的人儿给个解答吧

[解决办法]
while循环上加下这2句

p2->num = 100;
p2->next = NULL;

[解决办法]
while(p->next)
{
cout<<p->num<<endl;
p=p->next;
}

读书人网 >C++

热点推荐