I am creating a two-sided linked list. For that I implemented a Node with the following attributes:
struct Node {
public:
int Daten;
Node* Next = nullptr;
Node* Last = nullptr;
Node() {
}
Node(int Daten) {
this->Daten = Daten;
}
};
I then implemented a class, which adds Nodes to my Linked list. I can add two Nodes to the list, and all the references work perfectly. As soon as I create an instance of the third Node, the programm assumes that I am trying to reference the second element in the linked list. This behaviour can be seen, because when I debug the code. The linked list works Perfectly with two elements, but as soon as I call the "Node" Class to create the third object of it, the second element gets overwritten by it. This is the code on my Linked List Class.
class LList {
public:
Node head;
Node* NodePtr = &head;
void AddNode(int Key) {
if (NodePtr != &head) {
Node newnode(Key);
NodePtr = &head;
NodePtr->Next = &newnode;
newnode.Last = NodePtr;
NodePtr = NodePtr->Next;
}
else {
head.Daten = Key;
NodePtr = nullptr;
}
}
void printList() {
std::cout << "List status now: ";
Node* Localcopy = &head;
while (Localcopy != nullptr) {
std::cout << Localcopy->Daten << ", ";
Localcopy = Localcopy->Next;
}
std::cout << std::endl;
}
};
This is my main function where the code gets executed.
int main() {
LList mytree;
mytree.AddNode(7); // Works perfectly up to here.
mytree.printList();
mytree.AddNode(4); // Works perfectly up to here.
mytree.printList();
mytree.AddNode(2); // The first element points to the third Element, and the Second gets lost or overwritten.
mytree.printList();
return 0;
}
The output I get is the following:
List status now: 7,
List status now: 7, 4,
List status now: 7, 2,
That is all which is inside of my project. Why does this overwriting happen? Are there any mistakes that I am overlooking. How can I fix it?