注册 登录
编程论坛 C++教室

c++链表的问题

newCpp 发布于 2009-10-27 22:18, 436 次点击
#include <iostream>
#include <string>
using namespace std;
struct Student
{
 int age;
 string name;
    int h;
Student *hand;
};
int main()
{

 Student a,b,c, *p,*p1,*p3;
a.age=18;
a.name="fzq";
b.age=19;
b.name="fdghfgh";
c.age=20;
c.name="ddfgdf";
p=&a;
a.hand=&b;
b.hand=&c;
c.hand=0;
p1=p;
while(p!=0)

{
 int i=0;

 cout<<p->age<<" "<<p->name<<endl;
p=p->hand;

}
cout<<"hg"<<endl;
return 0;
}

这段代码里面的while循环体里面

p=p->hand;将这句话放置在

 cout<<p->age<<" "<<p->name<<endl;
的上面就会 出错这个是为什么?

为什么我将while(p->hand!=0)

这样写同上面那个将

p=p->hand;将这句话放置在

 cout<<p->age<<" "<<p->name<<endl;
有区别?

while(p->hand!=0)这样会不输出c的成员值?



p=p->hand;将这句话放置在

 cout<<p->age<<" "<<p->name<<endl;
这样的话,会不输出a的值,为什么链表尾的c可以省略输出

而a省略输出就出错了?这个是怎么回事?

我代码写错了??

谢谢高手帮忙指点一下下呀!!

O(∩_∩)O谢谢
2 回复
#2
东海一鱼2009-10-27 22:51
while(p!=0)
 
{
int i=0;
 
cout<<p->age<<" "<<p->name<<endl;
p=p->hand;
 
}
cout<<"hg"<<endl;
return 0;
}

p是一个链表的节点指针,while(p!=0)p不为空,不代表下一个节点指针不为空 p->hand != NULL ?????

理解了这个,就都明白了。

p=p->hand放在cout<<p->age<<" "<<p->name<<endl前面,直接操作的就是‘当前’下一个节点。可能已经为空了,肯定挂掉。



[ 本帖最后由 东海一鱼 于 2009-10-27 22:53 编辑 ]
#3
newCpp2009-10-27 23:01
恩,感谢地一塌糊涂!!!
说的太对了!确实是因为最后那个输出语句没有内容好输出,导致挂班的~
1