-1

I'm implementing linked list and stuck with push_back function. I have Node struct inside LinkedList class:

struct Node {
    T value;
    Node* next{ nullptr };
    Node* prev{ nullptr };
    Node() {}
    Node(T val, Node* n, Node* p) : value(val), next(n), prev(p) {}
    friend ostream& operator<<(ostream& os, const Node& x) {
        os << x.value;
        return os;
    }
};

In LinkedList class I have public members Node* head and Node* tail.
This is my push_back function:

void push_back(T val) {
    if (is_empty()) {
        Node NewNode;
        NewNode.value = val;
        NewNode.prev = nullptr;
        NewNode.next = nullptr;
        head = &NewNode;
        tail = &NewNode;
    }
    else {
        Node NewNode;
        NewNode.value = val;
        NewNode.prev = tail;
        NewNode.next = nullptr;
        tail->next = &NewNode;
        tail = &NewNode;
    }
}

If I insert only one element to the list and try to print head->value, program will print correct value, but if insert more, it will print something like -83295633.

  • `Node NewNode;` -- This is a local variable. What happens when that local variable goes out of scope? What will `head` and `tail` point to? That variable is no longer a valid one to point to, and that is what the duplicate link is all about. – PaulMcKenzie May 28 '22 at 13:27

0 Answers0