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.