1 Star 0 Fork 0

林进源 / 我错了

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
目录树 2.92 KB
一键复制 编辑 原始数据 按行查看 历史
林进源 提交于 2021-05-03 15:14 . add 目录树.
#include <iostream>
#include <string>
using namespace std;
typedef struct node* BTree;
typedef struct node {
string name;
BTree Catalog;//孩子
BTree Brother;//兄弟
bool flag;//判断目录和文件
}BTnode;
void DealStr(string str, BTree bt);//分离
BTree InsertFile(BTree bt, string name);
BTree Insertcatalog(BTree bt_Ca, string name);
int GetHeight(BTree BT, int h, string name, int flag);
void PrintfCat(BTree T, int h);
int main()
{
int n, i = 0;
string str;
/*初始化root结点*/
BTree T = new BTnode;
T->name = "root";
T->Brother = NULL;
T->Catalog = NULL;
T->flag = 1;
BTree bt = T;
cin >> n;
while (i < n)
{
cin >> str;
DealStr(str, bt);
i++;
}
PrintfCat(T, 1);
return 0;
}
void DealStr(string str, BTree bt)
{
while (str.size() > 0)
{
int pos = str.find('\\');
if (pos == -1)//只有一个字母,为文件
{
bt->Catalog = InsertFile(bt->Catalog, str);
return;
}
else//为目录
{
string name;
name.assign(str, 0, pos);
bt->Catalog = Insertcatalog(bt->Catalog, name);
bt = bt->Catalog;//移动到下一目录
while (bt != NULL && bt->flag == 1 && bt->name != name)
{
bt = bt->Brother;//找到刚才的目录位置
}
str.erase(0, pos + 1);//删除加入的字母
}
}
}
BTree InsertFile(BTree bt, string name)
{
if (bt == NULL || bt->flag == 0 && bt->name.compare(name) > 0)//情况1:bt为空,情况2:孩子为文件,且优先级大于之前的孩子
{
//作为兄弟插入
BTree NewFile = new BTnode;
NewFile->Brother = bt;
NewFile->flag = 0;
NewFile->Catalog = NULL;
NewFile->name = name;
return NewFile;
}
if (bt->flag != 1 && bt->name == name)//与当前文件名字一样
{
return bt;
}
bt->Brother = InsertFile(bt->Brother, name);//均不符合则转到其兄弟
return bt;
}
BTree Insertcatalog(BTree bt_Ca, string name)
{
if (bt_Ca == NULL || bt_Ca->flag == 0 || bt_Ca->name.compare(name) > 0)//情况1:目录为空 情况2:为文件 情况3:优先级大
{
BTree NewNode = new BTnode;
NewNode->name = name;
NewNode->flag = 1;
NewNode->Catalog = NULL;
NewNode->Brother = bt_Ca;
return NewNode;
}
if (bt_Ca->name == name)//与当前名字一样
{
return bt_Ca;
}
bt_Ca->Brother = Insertcatalog(bt_Ca->Brother, name);//转到兄弟
return bt_Ca;
}
int GetHeight(BTree BT, int h, string name, int flag)
{
if (BT == NULL)
{
return 0;
}
else if (BT->name == name && BT->flag == flag)
return h;
else
{
int l = GetHeight(BT->Brother, h, name, flag);
if (l != 0)
{
return 1;
}
else
return GetHeight(BT->Catalog, h + 1, name, flag);
}
}
void PrintfCat(BTree T, int h)
{
if (T != NULL)
{
h = GetHeight(T, h, T->name, T->flag);
for (int i = 1; i < h; i++)
{
cout << " ";
}
cout << T->name << endl;
PrintfCat(T->Catalog, h + 1);
PrintfCat(T->Brother, h);
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/lin-jinyuan/i-was-wrong.git
git@gitee.com:lin-jinyuan/i-was-wrong.git
lin-jinyuan
i-was-wrong
我错了
master

搜索帮助