题目描述:
在ZIP归档文件中,保留着所有压缩文件和目录的相对路径和名称。当使用WinZIP等GUI软件打开ZIP归档文件时,可以从这些信息中重建目录的树状结构。请编写程序实现目录的树状结构的重建工作。
输入格式:
输入首先给出正整数N(≤104≤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 <string.h>
typedef struct TNode {
int type;
char name[100];
struct TNode* Child_file[500];
struct TNode* Child_mulu[500];
int file;
int mulu;
} TNode, *Root;
int n;
Root root;
TNode* Search(Root Node, char* s) {
for (int i = 0; i < Node->mulu; i++)
if (strcmp(Node->Child_mulu[i]->name, s) == 0)
return Node->Child_mulu[i];
return NULL;
}
TNode* Creat_Mulu(Root* head, char* s) {
TNode* p = (TNode*)malloc(sizeof(TNode));
strcpy(p->name, s);
p->type = 1;
p->mulu = 0;
p->file = 0;
(*head)->Child_mulu[(*head)->mulu++] = p;
return p;
}
void Creat_File(Root* head, char* s) {
TNode* p = (TNode*)malloc(sizeof(TNode));
strcpy(p->name, s);
p->type = 0;
(*head)->Child_file[(*head)->file++] = p;
}
void Deal(char* s) {
char str[100];
TNode* Pre = root;
Root head = root;
int i, j;
i = j = 0;
while (s[i] != '\0') {
if (s[i] != '\\') {
str[j++] = s[i++];
} else {
str[j] = '\0';
Pre = Search(head, str);
if (!Pre)
head = Creat_Mulu(&head, str);
else
head = Pre;
j = 0;
i++;
}
}
if (s[i - 1] != '\\') {
str[j] = '\0';
Pre = Search(head, str);
if (!Pre)
Creat_File(&head, str);
}
}
void Initial() {
root = (TNode*)malloc(sizeof(TNode));
strcpy(root->name, "root");
root->file = 0;
root->mulu = 0;
root->type = 1;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
char s[100];
scanf("%s", s);
Deal(s);
}
}
int cmp(const void* a, const void* b) {
return strcmp((*(TNode**)a)->name, (*(TNode**)b)->name);
}
void Show(Root head, int n) {
for (int j = 0; j < n; j++)
printf(" ");
printf("%s\n", head->name);
if (head->type == 0)
return;
qsort(head->Child_file, head->file, sizeof(TNode*), cmp);
qsort(head->Child_mulu, head->mulu, sizeof(TNode*), cmp);
for (int i = 0; i < head->mulu; i++)
Show(head->Child_mulu[i], n + 1);
for (int i = 0; i < head->file; i++)
Show(head->Child_file[i], n + 1);
}
int main() {
Initial();
Show(root, 0);
return 0;
}