7-30 目录树

7-30 目录树(30 分)

在ZIP归档文件中,保留着全部压缩文件和目录的相对路径和名称。当使用WinZIP等GUI软件打开ZIP归档文件时,能够从这些信息中重建目录的树状结构。请编写程序实现目录的树状结构的重建工做。node

输入格式:

输入首先给出正整数N(104​​),表示ZIP归档文件中的文件和目录的数量。随后N行,每行有以下格式的文件或目录的相对路径和名称(每行不超过260个字符):数据结构

  • 路径和名称中的字符仅包括英文字母(区分大小写);
  • 符号“\”仅做为路径分隔符出现;
  • 目录以符号“\”结束;
  • 不存在重复的输入项目;
  • 整个输入大小不超过2MB。

输出格式:

假设全部的路径都相对于root目录。从root目录开始,在输出时每一个目录首先输出本身的名字,而后以字典序输出全部子目录,而后以字典序输出全部文件。注意,在输出时,应根据目录的相对关系使用空格进行缩进,每级目录或文件比上一级多缩进2个空格。ide

输入样例:

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

 参考了一个思路很清晰的代码,来自http://blog.csdn.net/Changxing898/article/details/52367514spa

#include<stdio.h> #include<stdlib.h> #include<string.h> #include<algorithm> typedef struct node *Node; struct node{ char *name; bool isMulu;                //先判断是否是目录,是目录才有file和mulu,不然只可能有brother
    Node File;                //指示本目录的子目录
    Node Mulu;                //指示本目录的子文件
    Node Brother;            //指示和本目录或文件平行的目录或文件
}Head; void Print(Node, int); void Read(); Node New(char*); Node InsertMulu(Node, char*); Node InsertFile(Node, char*); int main() { int n; scanf("%d", &n); Head.name = (char*)malloc(sizeof(char)* 5); strcpy(Head.name, "root"); Head.File = NULL; Head.Mulu = NULL; Head.Brother = NULL; Head.isMulu = true; for (int i = 0; i < n; i++) { getchar(); Read(); } Print(&Head, 0); return 0; } void Read() { char FileName[266]; Node temp = &Head; scanf("%s", FileName); char words[266]; int j, L = 0; for (int i = 0; i < strlen(FileName); i++) { if (FileName[i] == '\\'){ for (j = L; j < i; j++) words[j - L] = FileName[j]; words[j - L] = '\0'; temp->Mulu = InsertMulu(temp->Mulu, words); temp = temp->Mulu; while (strcmp(temp->name, words))temp = temp->Brother; L = i + 1; } } if (L < strlen(FileName)){ for (int j = L; j <= strlen(FileName); j++) words[j - L] = FileName[j]; temp->File = InsertFile(temp->File, words); } } Node InsertMulu(Node H, char *k) { if (!H || strcmp(H->name, k) > 0){ Node temp = New(k); temp->Brother = H; return temp; } if (strcmp(H->name, k) == 0)return H; H->Brother = InsertMulu(H->Brother, k); return H; } Node InsertFile(Node H, char*k) { if (!H || strcmp(H->name, k) > 0){ Node temp = New(k); temp->isMulu = false; temp->Brother = H; return temp; } H->Brother = InsertFile(H->Brother, k); return H; } Node New(char *k) { Node temp = (Node)malloc(sizeof(struct node)); temp->name = (char*)malloc(sizeof(char)*(strlen(k) + 1)); strcpy(temp->name, k); temp->Brother = NULL; temp->File = NULL; temp->Mulu = NULL; temp->isMulu = true; return temp; } void Print(Node H, int space) { if (H){ for (int i = 0; i < space; i++) printf(" "); printf("%s\n", H->name); if (H->isMulu == true) Print(H->Mulu, space + 2); Print(H->File, space + 2); Print(H->Brother, space); } }
别人家AC代码
相关文章
相关标签/搜索