#include
#include
using namespace std;
struct Node
{
int content;
Node *next;
};
void insert(Node *&h,int x)
{
Node *e=new Node;
e->content=x;
e->next=h;
h=e;
}
int main()
{
Node *p,*q1,*q2;
p=new Node;
int x;
p->next=NULL;
q2=p;
q1=p;
for(cin>>x;x!=-1;cin>>x)
{
insert(p,x);
}
while(q2->next!=NULL)
{
q2=q2->next;
q2=q2->next;
q1=q1->next;
}
cout<<q1->content;
return 0;
}
insert函数有问题,while内部有问题,在结构体中没有显式定义构造函数,会有隐患。
首先说insert函数内部,你是想创建成一个循环链表?那对于while来说,next怎么会出现空指针?当然,由于插入的位置有问题(插到链表头,而链表头结点的next为空),造成while会出现结束点。
其次是在while内部,q2指向了其后第二个结点,q1指向了其后第一个结点,无意义。
没有显式定义构造函数,系编译器自动添加无参构造器,但建议使用带参构造器来创建需要添加或初始化的结点。
http://www.cnblogs.com/scrat/archive/2012/08/14/2638740.html
参考学习。。。