如何添加到双向链表的第一个?

how to add to the first of a 2-way linked list?

我正在尝试使用 class 在 C++ 中创建一个双向链表,但我遇到了一个烦人的问题,无法将节点添加到列表的第一个!
这是 Node class:

class node{
public:
    node(int d = 0, node *p = NULL, node *n = NULL):data(d), pre(p), next(n){}

    void setPrevious(node *p){this->pre = p;}
    void setNext(node *n){this->next = n;}
    void setData(int d){this->data = d;}

    int data;
    node *pre, *next;

};

这是我创建第一个节点的方法:

node *head = new node(), *current = new node(), *last = new node();
cout<<msg_data;
// 'd' is an Integer variable
cin>>d;
current->setData(d);
head = new node(0, 0, current);

这就是我尝试将节点添加到列表第一个的方式:

cout<<"enter 'data' for list: ";
// 'd' is an Integer variable
cin>>d;
node *tmp = new node(d, 0, head);
head = tmp;

当我想首先添加节点时,它会在值后为 'data' 添加一个“0”!前任。我想将“21”添加到列表的第一个,但它向列表添加了 21 和 0!

两个观察结果:

查看创建第一个节点的代码,它创建的不是一个节点,而是四个节点。看来你完全误解了什么。在纸上画出列表应该是什么样子,你就会明白的。

您将额外节点添加到列表第一个节点的代码似乎没问题。