1

Attempted to build a doubly linked list and printing it out. However, I received a linker command failed after adding "static Node* lastAdded". Not sure what the reason is.

Also, for the head node, I would like leave "int data" uninitialized. Is there a better way to leaves data uninitialized than what I have below?

#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;
    }
}

1 Answers1

0

You need to define/initialize your static variable which declared inside the class

static inline Node* lastAdded {nullptr};

in c++17 you can use inline to define static variable

#include <iostream>
#include <string>

using namespace std;

struct Node {
    static inline Node* lastAdded {nullptr};

    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->next; temp != nullptr; temp=temp->next) {
        cout << temp->data << endl;
    }
}

output

1
12
Program ended with exit code: 0
Hariom Singh
  • 3,512
  • 6
  • 28
  • 52