问题描述:
在给定Linux文件信息的情况下,讲文件以树的形式展现出来。类似Linux下的tree命令。输入和输出如下:
输入解释:
第一行为总的文件数目:n
后面输入的每行从0计数,代表紧接着输入文件的id号,输入文件名+“空格” + 该文件父id号,pid=-1代表根节点。
例如:my-app 文件id为0,src文件id为1,pom.xml文件id为2,src和pom.xml的父文件为my-app.
代码如下:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct filenode{
string filename;
int id;
int pid;
filenode(string name, int id_temp, int pid_temp):filename(name),id(id_temp),pid(pid_temp){}
};
bool sortbyname(const filenode a, const filenode b){
if(a.filename<b.filename)
return true;
else
return false;
}
bool isFolder(vector<filenode> filenodes, int pid)
{
for(int i = 0; i < filenodes.size(); i++)
{
if(filenodes[i].pid == pid)
return true;
}
return false;
}
void printTree(vector<filenode> filenodes, int depth, int id, int block)
{
int n = filenodes.size();
int fathernode = id;
if(id == -1){
for(int i = 0; i < n; i++){
if(filenodes[i].pid == -1){
fathernode = filenodes[i].id;
break;
}
}
}
vector<filenode> childnodes = vector<filenode>();
for(int i = 0; i < n; i++){
if(filenodes[i].pid == fathernode)
childnodes.push_back(filenodes[i]);
}
printf("%s\n",filenodes[fathernode].filename.c_str());//打印文件名
if(childnodes.size() != 0){
sort(childnodes.begin(), childnodes.end(), sortbyname);
for(int j = 0; j < childnodes.size(); j++){
int k = block;
while(k--) printf(" ");
int k2 = depth - block;
while(k2--) printf("| ");
if(isFolder(filenodes,childnodes[j].id)){
if(j == childnodes.size() - 1){
printf("|-- ");
printTree(filenodes, depth + 1, childnodes[j].id, block + 1);
}else{
printf("|-- ");
printTree(filenodes, depth + 1, childnodes[j].id, block);
}
}else{
if(j == childnodes.size() - 1){
printf("|-- %s\n",childnodes[j].filename.c_str());
}else{
printf("|-- %s\n",childnodes[j].filename.c_str());
}
}
}
}
}
int main()
{
int n = 0;
cin>>n;
vector<filenode> filenodes = vector<filenode>();
for(int i = 0; i < n; i++){
char k[1000];
cin>>k;
int temp;
cin>>temp;
filenodes.push_back(filenode(string(k), i, temp));
}
cout<<"print the tree of files"<<endl;
printTree(filenodes, 0, -1, 0);
system("pause");
return 1;
}