題意:按照指定格式輸出目錄樹(shù)。要求同一層下的file要按文件名排序。
解題步驟:
1.用deep記錄當(dāng)前目錄深度,遇到dir,deep++,遇到] deep--
2.用strlist記錄所有未輸出的file,用棧stack記錄當(dāng)前目錄下的file表的開(kāi)始下標(biāo)。遇到]或者*則輸出當(dāng)前目錄下的所有file,并從strlist中刪除,相應(yīng)的下標(biāo)出棧(stack).
代碼
1
import java.io.*;
2
import java.util.*;
3
class Main
4

{
5
public static ArrayList<Integer> stack = new ArrayList<Integer>();
6
public static ArrayList<String> strlist = new ArrayList<String>();
7
public static void main(String[] args)
8
{
9
10
Scanner sc = new Scanner(System.in);
11
String strt = sc.nextLine();
12
13
int deep = 0;
14
int seq = 1;
15
boolean newdataset = true;
16
while(!strt.equals("#"))
17
{
18
if(newdataset)
19
{
20
if(seq != 1)
21
System.out.println();
22
System.out.println("DATA SET " + seq++ + ":");
23
System.out.println("ROOT");
24
25
push(0);// push()
26
newdataset = false;
27
}
28
if(strt.equals("*"))
29
{
30
outFileStrs(deep);
31
deep = 0;
32
strlist.clear();
33
stack.clear();
34
newdataset = true;
35
36
}
37
else if(strt.startsWith("d"))
38
{
39
40
deep++;
41
push(strlist.size());//push()
42
43
outSpace(deep);
44
System.out.println(strt);
45
46
}
47
else if(strt.startsWith("f"))
48
{
49
strlist.add(strt);
50
}
51
else if(strt.equals("]"))
52
{
53
outFileStrs(deep);
54
deep--;
55
}
56
57
strt = sc.nextLine();
58
}
59
}
60
public static void outSpace(int deep)
61
{
62
if(deep == 0)
63
return;
64
for(int i = 0; i < deep; i++)
65
{
66
System.out.print("| ");
67
}
68
}
69
public static void outFileStrs(int deep)
70
{
71
TreeSet<String> tset = new TreeSet<String>();
72
int p = pop();
73
int size = strlist.size();
74
for(int i = p; i < strlist.size(); i++)
75
{
76
tset.add(strlist.get(i));
77
78
}
79
for(int i = size - 1; i >= p; i--)
80
{
81
strlist.remove(i);
82
}
83
for(String str : tset)
84
{
85
outSpace(deep);
86
System.out.println(str);
87
}
88
89
}
90
public static void push(Integer n)
91
{
92
stack.add(n);
93
}
94
public static Integer pop()
95
{
96
int size = stack.size();
97
Integer n = stack.get(size - 1);
98
stack.remove(size - 1);
99
return n;
100
}
101
}
102
解題步驟:
1.用deep記錄當(dāng)前目錄深度,遇到dir,deep++,遇到] deep--
2.用strlist記錄所有未輸出的file,用棧stack記錄當(dāng)前目錄下的file表的開(kāi)始下標(biāo)。遇到]或者*則輸出當(dāng)前目錄下的所有file,并從strlist中刪除,相應(yīng)的下標(biāo)出棧(stack).


1

2

3

4



5

6

7

8



9

10

11

12

13

14

15

16

17



18

19



20

21

22

23

24

25

26

27

28

29



30

31

32

33

34

35

36

37

38



39

40

41

42

43

44

45

46

47

48



49

50

51

52



53

54

55

56

57

58

59

60

61



62

63

64

65



66

67

68

69

70



71

72

73

74

75



76

77

78

79

80



81

82

83

84



85

86

87

88

89

90

91



92

93

94

95



96

97

98

99

100

101

102
