Good day,
I have a sample LinkedList, which is a very basic class for me to learn C++ with. At the moment i'm trying to add new nodes to my linked list using a class etc, and I encountered a very odd bug.
Here's my LinkedList.h:
struct Node {
Node* next;
int value;
};
class LinkedList {
private:
Node* root;
public:
LinkedList();
void print();
void add(int val);
~LinkedList();
};
And here's my LinkedList.cpp
#include "LinkedList.h"
#include <iostream>
using namespace std;
LinkedList::LinkedList() {
root = NULL;
}
LinkedList::~LinkedList() {
}
void LinkedList::add(int val) {
Node node;
node.next = NULL;
node.value = val;
if (root != NULL)
node.next = root;
root = &node;
cout << root->value << endl; // TEST PRINT 1
}
void LinkedList::print() {
cout << root->value <<endl; // TEST PRINT 2
}
This is my main.cpp:
#include "LinkedList.h"
#include <iostream>
using namespace std;
int main() {
LinkedList list;
list.add(5);
list.print();
}
This code should simply create a new node with the value '5' and make it the root. When I add a new number a different node should be created and this new node should be the root with the old root as its 'next' node.
I have two debug messages, located near 'TEST PRINT 1' and 'TEST PRINT 2'. Both lines are exactly the same, yet the first print gives me the correct value (which is 5) while the second print gives me a very weird negative number (-858993460).
What have I done wrong?