链表创建途中遇到的问题

#include <iostream>
#include<new>
using namespace std;
struct node{
int data;
node *next;
};
class list{
public:
node *head;
list(){head=null};
list(int x){
node *p,*q;
p=q=head;
head=new node;

head->next=null;
head->data=0;
for(int i=1;i<x;i++)
{
p=new node;
p->data=i;
p->next=null;
q->next=p;
q=p;
}q->next=null;


};
void print()
{
node *r=head;
if(head==null)
cout<<"have no number"<<endl;
else while(r!=null)
{cout<<r->data;
r=r->next;}
}
}
int main()
{
int n;
cout<<"input number>>"<<endl;
cin>>n;
list l1;
list l2(n);
cout<<"list1"<<endl;
l1.print();
cout<<"list2"<<endl;
l2.print();

return 0;
}

论该程序的list 2为什么无法输出全部链表值?
错误总结一:
请看如下改进:
#include <iostream>
#include<new>
using namespace std;
struct node{
int data;
node *next;
};
class list{
public:
node *head;
list(){head=NULL;};
list(int x){
node *p,*q;

head=new node;
p=q=head;//the imporant position
head->next=NULL;
head->data=0;
for(int i=1;i<x;i++)
{
p=new node;
p->data=i;
p->next=NULL;
q->next=p;
q=p;
}q->next=NULL;


};
void print()
{
node *r=head;
if(head==NULL)
cout<<"have no number"<<endl;
else while(r!=NULL)
{cout<<r->data;
r=r->next;}
}
};
int main()
{
int n;
cout<<"input number>>"<<endl;
cin>>n;
list l1;
list l2(n);
cout<<"list1"<<endl;
l1.print();
cout<<"list2"<<endl;
l2.print();

return 0;
}
之所以第一段代码的list2无法输出全部链表的原因是p,q若在head创建存储空间(new)之前赋值,三个都指向一的个空间并不是head=new node的那个空间
、、、、、、、、、、、、、、、
node *p,*q;
cout<<head<<endl;//1
head=new node;
cout<<head<<endl;//2
。。。。。。。。。。。。。。可以通过部分添加如上两行反映1,2地址是不同的。
而导致的后边创建链表空间用p,q,根本就和head没有关系。即head就只有表头一个空间。

原文地址:https://www.cnblogs.com/8335IT/p/4736094.html