Pointers 节点的返回和下一个指针

Pointers 节点的返回和下一个指针,pointers,Pointers,我是C++新手。我现在尝试创建一个具有来回指针的类。我的代码如下: #include<iostream> using namespace std; class Node { public: Node(int d, Node*k = NULL, Node*q = NULL) :data(d), back(k), next(q){}; int data; Node*next; // point to next value on the list Node*back; //

我是C++新手。我现在尝试创建一个具有来回指针的类。我的代码如下:

#include<iostream>
using namespace std;

class Node
{
public:
Node(int d, Node*k = NULL, Node*q = NULL) :data(d), back(k), next(q){};      
int data;
Node*next; // point to next value on the list
Node*back;  // point to back value on the list

};

int main()
{
int n;
Node*p = NULL;  
Node*k = NULL;  //k is back
while (cin >> n)
{
    p = new Node(n,k);
    p->back->next = p;
    k = p;

}

for (; p; p = p->back)
    cout << p->data << "->";
cout << "*\n";
system("pause");

}
#包括
使用名称空间std;
类节点
{
公众:
节点(intd,Node*k=NULL,Node*q=NULL):数据(d),返回(k),下一个(q){};
int数据;
Node*next;//指向列表上的下一个值
Node*back;//指向列表上的后向值
};
int main()
{
int n;
Node*p=NULL;
Node*k=NULL;//k回来了
while(cin>>n)
{
p=新节点(n,k);
p->back->next=p;
k=p;
}
对于(;p;p=p->back)

循环
p->back
的第一次迭代中的cout data为
NULL
。由于取消了对它的引用,因此会出现访问冲突。请改为编写以下内容:

while (cin >> n)
{
    p = new Node(n,k);
    if (p->back != NULL) // p->back == NULL in the first iteration
      p->back->next = p;
    k = p;
}