The first error you'll get, is when you try to use node::node()
. If you look at your code:
...
node::node()
{
next = new node;
}
...
node::node()
is a constructor of a class. A constructor of a class is a function that will be executed when you create an instance of that class. Let's say you create a new node:
node n;
node::node()
is called. But hey, what is it doing?
next = new node;
It's creating a new node... which means calling node::node()
again, and again ad infinitum. This is why your program crashed.
Back to the linked list
If you want to write a linked list, you don't just need nodes. Ideally, you want to encapsulate all the nodes such that it's hidden from anyone who is using your linked list library. I won't go into all the text book information, but briefly:
- It makes sure that no one can accidentally modify your nodes (makes sure that they behave in an intended way)
- Less code on the screen. Your users won't get overwhelmed with all the little details. (All the linked list code can be kept in another file, and the user can just focus on what s/he needs to do. )
Here's an example implementation.
#include <iostream>
// Declaration can be put into LinkedList.h
struct node {
node* next_node;
char* some_data;
node()
{
next_node = nullptr;
}
};
class LinkedList
{
node* head;
node* tail;
public:
LinkedList();
~LinkedList() { /* if you do this properly, you need to clear up all the nodes you have created... */}
void AddNode(char* data);
void PrintNodeData();
};
// Method implementation (The details) can be put into LinkedList.cpp
LinkedList::LinkedList()
{
head = nullptr;
}
void LinkedList::AddNode(char* data)
{
node* new_node = new node();
new_node->some_data = data;
if (head == nullptr)
{
// initialise the first node
head = new_node;
}
else
{
node*n = head;
while (n->next_node != nullptr)
{
// move on to the next node
n = n->next_node;
}
n->next_node = new_node;
}
}
void LinkedList::PrintNodeData()
{
// Loop through all the nodes
for (node*n = head; n != nullptr; n = n->next_node)
{
std::cout << "Data: " << n->some_data << std::endl;
}
}
// this is all the code the user has to pay attention to
int main()
{
LinkedList ll;
ll.PrintNodeData(); // prints nothing, since head == nullptr at this point
ll.AddNode("Data for my 1st node.");
ll.AddNode("Data for my 2nd node.");
ll.AddNode("Data for my 3rd node.");
ll.AddNode("Data for my 4th node.");
ll.PrintNodeData(); // prints all the data
return 0;
}
Hope this helps, and I hope you enjoy your journey of self-discovery. :-)