1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package adt.trie;
21
22 import java.util.ArrayList;
23 import java.util.List;
24
25 class TriePath<T> {
26
27 List<PathNode<T>> path;
28
29 public TriePath(Node<T> root) {
30 path = new ArrayList<PathNode<T>>();
31 path.add(new PathNode<T>(root));
32
33 while (!path.get(path.size() - 1).node.hasData) {
34 PathNode<T> pathNode = path.get(path.size() - 1);
35 pathNode.position = 0;
36 if (pathNode.node.nodes.size() == 0)
37 break;
38 Node<T> node = pathNode.node.nodes.get(0);
39 path.add(new PathNode<T>(node));
40
41 }
42 }
43
44 public boolean hasNext() {
45 while (true) {
46 if (path.size() == 0)
47 return false;
48 PathNode<T> pathNode = path.get(path.size() - 1);
49 if (!pathNode.hasMore()) {
50
51 path.remove(path.size() - 1);
52 } else {
53 return true;
54 }
55 }
56 }
57
58 public TrieIterEntry<T> next() {
59 if (!hasNext())
60 return null;
61 PathNode<T> pathNode = path.get(path.size() - 1);
62 if (!pathNode.selfDone) {
63 pathNode.selfDone = true;
64
65
66 return new TrieIterEntry<T>(buildPath(), null);
67 }
68 pathNode.position += 1;
69 Node<T> nextNode = pathNode.node.nodes.get(pathNode.position);
70 path.add(new PathNode<T>(nextNode));
71
72 pathNode = path.get(path.size() - 1);
73
74 while (!path.get(path.size() - 1).node.hasData) {
75 pathNode.position = 0;
76 Node<T> node = pathNode.node.nodes.get(0);
77 path.add(new PathNode<T>(node));
78
79 pathNode = path.get(path.size() - 1);
80 }
81
82 if (!pathNode.selfDone)
83 pathNode.selfDone = true;
84
85 return new TrieIterEntry<T>(buildPath(), null);
86 }
87
88 private String buildPath() {
89 StringBuilder strb = new StringBuilder();
90 for (int i = 0; i < path.size(); i++) {
91 strb.append(path.get(i).node.word);
92 }
93 return strb.toString();
94 }
95 }