题目:
在ZIP归档文件中,保留着所有压缩文件和目录的相对路径和名称。当使用WinZIP等GUI软件打开ZIP归档文件时,可以从这些信息中重建目录的树状结构。请编写程序实现目录的树状结构的重建工作。
输入格式:
输入首先给出正整数N(≤1e4),表示ZIP归档文件中的文件和目录的数量。随后N行,每行有如下格式的文件或目录的相对路径和名称(每行不超过260个字符):
路径和名称中的字符仅包括英文字母(区分大小写);
符号“\”仅作为路径分隔符出现;
目录以符号“\”结束;
不存在重复的输入项目;
整个输入大小不超过2MB。
输出格式:
假设所有的路径都相对于root目录。从root目录开始,在输出时每个目录首先输出自己的名字,然后以字典序输出所有子目录,然后以字典序输出所有文件。注意,在输出时,应根据目录的相对关系使用空格进行缩进,每级目录或文件比上一级多缩进2个空格。
输入样例:
7
b
c\
ab\cd
a\bc
ab\d
a\d\a
a\d\z\
输出样例:
root
a
d
z
a
bc
ab
cd
d
c
b
参考大佬的代码
链接:PTA习题解析——目录树
代码搬运工就是我了,记下来当模板
//https://www.cnblogs.com/linfangnan/p/12617499.html
#include<bits/stdc++.h>
using namespace std;
typedef struct CSNode
{
string data; //数据域
struct CSNode* firstchild; //指向对应长子结点的指针域
struct CSNode* rightsib; //指向对应右兄弟结点的指针域
int flag; //判断是文件还是目录的 flag
} CSNode, * CSTree;
CSTree insertNode(CSTree t,string s,int flag)
{
CSTree node=new CSNode;
CSTree pre=t,ptr;
node->data=s;
node->firstchild=node->rightsib=NULL;
node->flag=flag;
if(t->firstchild==NULL)
{
t->firstchild=node;
return t->firstchild;
}
ptr=t->firstchild;//由于根结点本身插入时,是插在长子位,因此另外设置 pre 当前驱结点,ptr 当 pre 的后继,比较好写
while (ptr != NULL && ((ptr->flag>node->flag)||(ptr->flag==node->flag&&s>ptr->data)))
{
pre = ptr;
ptr = ptr->rightsib;
}
//要先判空,不然有段错误
if(ptr==NULL)//无处可插入,插在链尾
{
node->rightsib=pre->rightsib;
pre->rightsib=node;
return node;//接下来以 node 为根目录操作
}
else if(ptr->data==node->data&&ptr->flag==node->flag)//目录或文件已存在
{
delete node;
return ptr;
}
else
{
if(pre->data==t->data)//插在根目录的长子位(pre)没改变
{
node->rightsib=pre->firstchild;
pre->firstchild=node;
}
else//正常插入
{
node->rightsib=pre->rightsib;
pre->rightsib=node;
}
return node;
}
}
void CreatTree(CSTree pre,string s)
{
int index=0;
getline(cin,s);
for(int i=0; i<s.length(); i++)
{
if(s[i]=='\\')
{
pre=insertNode(pre,s.substr(index,i-index),1);
index=i+1;
}
}
if(index<s.length())
pre=insertNode(pre,s.substr(index,s.length()-index),0);
}
void print(CSTree t,int space)
{
if(t==NULL)
return;
for(int i=0;i<space;i++)
cout<<' ';
cout<<t->data<<endl;
print(t->firstchild,space+2);
print(t->rightsib,space);
}
int main()
{
//freopen("in.txt","r",stdin);
int n;
CSTree tree=new CSNode;
tree->data="root";
tree->firstchild=tree->rightsib=NULL;
tree->flag=1;
cin>>n;
string s;
for(int i=0;i<=n;i++)
CreatTree(tree,s);
print(tree,0);
}