1.源碼實(shí)現(xiàn)
#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; //數(shù)據(jù)域
bool flag; //是否是目錄
public:
vector<CSNode> childs; //子節(jié)點(diǎn)
};
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.運(yùn)行及其結(jié)果
$ ./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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。