1.源码实现
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class CSNode {
public:
CSNode()
{
this->data = "";
this->flag = false;
}
CSNode(string data, bool flag = false)
{
this->data = data;
this->flag = flag;
}
~CSNode()
{
this->childs.clear();
}
void setData(string data)
{
this->data = data;
}
string getData()
{
return this->data;
}
void setFlag(bool flag)
{
this->flag = flag;
}
int addChild(CSNode &child)
{
int size = childs.size();
this->childs.push_back(child);
return size;
}
int addChild(string data, bool flag = false)
{
CSNode child(data, flag);
vector<CSNode>::iterator i;
int j = 0;
for(i=childs.begin(); i!=childs.end(); ++i, ++j)
{
if(i->data == data)
{
return j;
}
}
this->childs.push_back(child);
return j;
}
CSNode *getChild(int index)
{
if(index >= childs.size())
{
return NULL;
}
else
{
return &childs[index];
}
}
private:
string data; //数据域
bool flag; //是否是目录
public:
vector<CSNode> childs; //子节点
};
class CSTree {
public:
CSTree()
{
root.setData("root");
root.setFlag(true);
}
~CSTree()
{
}
void createNode(string s)
{
CSNode *pre = &root;
int j = 0;
int index = 0;
int i;
for(i=0; i<s.length(); i++)
{
if(s[i] == '/')
{
j = pre->addChild(s.substr(index, i-index), true);
//cout << "pre->data: " << pre->getData() << " " << s.substr(index, i-index) << endl;
index = i + 1;
pre = pre->getChild(j);
}
}
if(index < s.length())
{
//cout << s.substr(index, i-index) << endl;
j = pre->addChild(s.substr(index, i-index), false);
}
}
void print(CSNode *t, string s)
{
string u;
if(t == NULL)
{
return;
}
if(t->childs.size() >= 1)
{
for(int i=0; i<t->childs.size(); i++)
{
u = s + "/" + t->getData();
print(&(t->childs[i]), u);
}
}
else
{
cout << s + "/" + t->getData() << endl;
}
}
void print()
{
print(&root, "");
}
private:
CSNode root;
};
int main()
{
CSTree tree;
int n;
cin >> n;
string s;
for(int i=0;i<n;i++)
{
cin >> s;
tree.createNode(s);
}
tree.print();
return 0;
}
2.编译源码
$ g++ -o cstree cstree.cpp -std=c++11
3.运行及其结果
$ ./cstree
4
111/222/333
111/222/444
111/333/444
111/222/444
/root/111/222/333
/root/111/222/444
/root/111/333/444