<分区>
试图建立一个双向链表并打印出来。但是,我在添加“static Node* lastAdded”后收到链接器命令失败。不知道是什么原因。
此外,对于头节点,我希望“int data”保持未初始化状态。有没有比我下面的更好的方法来保持数据未初始化?
#include <iostream>
#include <string>
using namespace std;
struct Node {
static Node* lastAdded;
Node(const int data); // General data node constructor
Node(); // head constructor
static void push(Node* previousNode);
int data;
Node* previous;
Node* next;
};
Node::Node(const int data) {
this->data = data;
}
Node::Node() {
// Note that data is left uninitalized for head node
previous = nullptr;
next = nullptr;
lastAdded = this;
}
static void push(Node* currentNode, Node* previousNode) {
previousNode->next = currentNode;
currentNode->previous = previousNode;
currentNode->next = nullptr;
Node::lastAdded = currentNode;
}
int main()
{
Node* head = new Node();
push(new Node(1), Node::lastAdded);
push(new Node(12), Node::lastAdded);
for (Node* temp = head; temp->next != nullptr; temp++) {
if (temp->previous == nullptr)
temp++;
cout << temp->data << endl;
}
}