7-9 目录树 (30 分)
在ZIP归档文件中,保留着所有压缩文件和目录的相对路径和名称。当使用WinZIP等GUI软件打开ZIP归档文件时,可以从这些信息中重建目录的树状结构。请编写程序实现目录的树状结构的重建工作。
输入格式:
输入首先给出正整数N(≤104),表示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
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
typedef struct LNode{
// string name;
char name[500];
int IsMulu;
struct LNode * brother;
struct LNode * child_file;
struct LNode * child_mulu;
}LNode;
LNode* init(char *s,int flag){//只要是指针都需要开辟空间,不要忘记了!
LNode *p=(LNode*)malloc(sizeof(LNode));
p->brother=(LNode*)malloc(sizeof(LNode));
p->child_file=(LNode*)malloc(sizeof(LNode));
p->child_mulu=(LNode*)malloc(sizeof(LNode));
//p->name=(char *)malloc(sizeof(char)*100);
//p->name=s;
strcpy(p->name,s);
p->brother=NULL;
p->child_file=NULL;
p->child_mulu=NULL;
p->IsMulu=flag;
return p;
}
LNode *Insert_Mulu(LNode * p,char* s){//返回应该的子目录
if(!p||strcmp(p->name,s)>0){//需要进行创建 按照顺序进行的
//一旦比他还大,说明后面都没有了
LNode * temp=init(s,1);
temp->brother=p;
return temp;
}
if(strcmp(p->name,s)==0) return p;//与file略有不同,因为文件是一定要添加的
p->brother=Insert_Mulu(p->brother,s);
return p;
}
LNode * Insert_file(LNode *p,char* s){
if(!p||strcmp(p->name,s)>0){
LNode *temp=init(s,0);
temp->brother=p;
return temp;
}
p->brother=Insert_file(p->brother,s);
return p;
}
void Print(LNode *p,int coun){
if(p){
//cout<<"come"<<endl;
for(int i=0;i<coun;i++) cout<<" ";
cout<<p->name<<endl;
if(p->IsMulu==1) Print(p->child_mulu,coun+2);
Print(p->child_file,coun+2);
Print(p->brother,coun);
}else return;
}
int main(){
int n;cin>>n;
//getchar();
LNode * root=init("root",1);
while(n--){
LNode * head=root;
//string s;
getchar();
char s[500];
cin>>s;
int len=strlen(s);
char t[500];int i;
int num=0;
for(i=0;i<len;i++){
if(s[i]=='\\'){
// cout<<t<<endl;
t[num]='\0';
head->child_mulu=Insert_Mulu(head->child_mulu,t);
head=head->child_mulu;
while(strcmp(head->name,t)!=0) head=head->brother;//定位到新的节点 因为存在<的情况导致最终返回的//不一定是新的位置
num=0;
}
else t[num++]=s[i];
}
if(i==len&&s[len-1]!='\\'){//添加文件
t[num]='\0';
//cout<<"file "<<t<<endl;
head->child_file=Insert_file(head->child_file,t);
//t.clear();
num=0;
}
}
Print(root,0);
}