I've created this example code, but I just can't make it work. I want to create children from a parent node, in a way that every children has one parent, and each have a pointer to its parent. The first parent's pointer is the nullpointer. Now the question is, if I am somewhere at the end of the tree's branch, how can I return to the first parent step by step, and write out the history?
For the sake of simplicity, in this example I've created a linear graph with one simple path.
I discovered that if I want to dereference a node's parent's node for the second time, I already get fake results, and I can't reach further than the first parent. So I can only dereference the current node's parent. Why is that? I have seen that in linked-lists people store every pointer, but I would like to avoid that. The goal is, every node is stored in a list<Node>
, and each of them stores only its parents pointer, so from every node we can trace back the first parent.
#include <iostream>
#include <list>
using namespace std;
struct Node
{
int node;
Node *parent;
};
void create (Node parent, list<Node>& graph)
{
if (graph.size() < 10)
{
Node nn;
nn.node = parent.node+1;
nn.parent = &parent;
graph.push_back(nn);
create(nn, graph);
}
}
int main()
{
list<Node> graph;
Node parent;
parent.node = 0;
parent.parent = nullptr;
graph.push_back(parent);
create(parent, graph);
for (auto i : graph)
{
cout << i.node << " ";
}
cout << endl << endl;
auto it = graph.begin();
advance(it, 3);
cout << (*it).node << endl;
cout << (*(*(*it).parent).parent).node;
return 0;
}