Mam nasledovny kod. Je tam jeden template objekt Node ktory reprezentuje uzol stromu. Kazdy uzol moze obsahovat dynamicky pocet poduzlov. Na kratkom priklade mam vytvoreny jeden uzol ktory obsahuje 3 poduzly. Ak chcem prechadzat poduzly od prveho prvku az po posledny tak vsetko funguje, ale akonahle prechadzam opacne tak sa mi program zacykly. Neviete kde tam mam chybu?
#include <list>
template <class T>
class Node{
Node* root = nullptr;
typename std::list<Node*>::iterator root_iter;
std::list<Node*> line; //poduzly
T data;
public:
enum eInsertPos_t{FRONT, BACK};
Node(const T &t):data(t){}
T &operator*(){return data;}
const T& operator*()const{return data;}
T& GetData(){return data;}
const T& GetData()const{return data;}
T CopyData()const{return data;}
Node* Top()const{
Node* n;
for(n = const_cast<Node*>(this); n->root; n = n->root);
return n;
}
void InsertRoot(Node* node, eInsertPos_t pos = BACK){
if(root){
node->root = root;
node->root_iter = root_iter;
*root_iter = node;
root = node;
}
else{
root = node;
node->line.push_back(this);
root_iter = std::prev(node->line.end());
}
if(pos == BACK){
node->line.push_back(this);
root_iter = std::prev(node->line.end());
}
else{ //FRONT
node->line.push_front(this);
root_iter = node->line.begin();
}
}
void InsertLeaf(Node* node, eInsertPos_t pos = BACK){
node->Pop();
node->InsertRoot(this, pos);
}
void Pop(){
if(root){
root->line.erase(root_iter);
root = nullptr;
}
}
Node* Next()const{
if(root){
typename std::list<Node*>::const_iterator i = root_iter;
i++;
if(i != root->line.cend())return *i;
}
return nullptr;
}
// Toto nefunguje spravne:
Node* Prew()const{
if(root){
typename std::list<Node*>::const_iterator i = root_iter;
if(i == root->line.cbegin())return nullptr; //podmienka sa vyhodnoti ako false aj ked obydva iteratory ukazuju na ten isty pointer, preco?
i--; //iterator sa nedekrementuje, preco?
return *i;
}
return nullptr;
}
Node* Up()const{
return root;
}
Node* Down(eInsertPos_t pos = FRONT)const{
if(line.empty())return nullptr;
if(pos == FRONT)return line.front();
else return line.back();
}
Node* Front()const{
if(root)return root->line.front();
else return this;
}
Node* Back()const{
if(root)return root->line.back();
else return this;
}
};
#include <iostream>
using namespace std;
int main(){
Node<int> n1(1);
Node<int> n2(2);
Node<int> n3(3);
Node<int> n4(4);
//Node<int>* tree = n4.Top();
n2.InsertRoot(&n1);
n3.InsertRoot(&n1);
n1.InsertLeaf(&n4);
/*
* 1 -> 2
* -> 3
* -> 4
*
*/
for(auto i = n1.Down(); i; i = i->Next())cout << **i << ", "; //funguje pravne
cout << endl;
for(auto i = n1.Down(Node<int>::BACK); i; i = i->Prew()) //zacykli sa
{
cout << **i << ", ";
cin.get();
}
cout << endl;
return EXIT_SUCCESS;
}