创建和测试一个 Java Trie 类,我的主类由于某种原因挂断了,并且运行程序永远不会终止。
import java.util.*;
public class Trie<T> {
private Node<T> root;
private int count;
public Trie(T rootContent){
root= new Node<T>(rootContent);
count=0;
}
public void insert(T[] content){
Node<T> current=root;
if(content !=null){
if(content.length==0){
current.setFlag(true);
}
for(int i=0; i<content.length;i++){
Node<T> child=current.getChild(content[i]);
if(child!=null){
current=child;
}
else{
current=current.addChildren(content[i]);
}
if(i==content.length-1){
if(current.isLast()){
current.setFlag(true);
count++;
}
}
}
}
}
public boolean search(T[] content){
Node<T> current=root;
for(int i=0;i<content.length;i++){
if(current.getChild(content[i])==null){
return false;
}
else{
current=current.getChild(content[i]);
}
}
if(current.isLast()){
return true;
}
else{
return false;
}
}
public int getCount(){
return count;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("number entries: ");
sb.append(count);
return sb.toString();
}
private static class Node<T>{
private T content;
private boolean endFlag;
public List<Node<T>> children=new ArrayList<Node<T>>();
public Node(T content){
this.content=content;
this.endFlag=false;
this.children=new ArrayList<Node<T>>();
}
public T getContent(){
return content;
}
public Node<T> addChildren(T content){
Node<T> t=new Node<T>(content);
children.add(t);
return t;
}
public Node<T> getChild(T content){
if(children!=null){
for(Node<T> t : children){
if(t.getContent().equals(content)){
return t;
}
}
}
return null;
}
public void setFlag(boolean endFlag){
this.endFlag=endFlag;
}
public boolean isLast(){
return endFlag;
}
}
public static void main(String[] args) {
Trie file1=new Trie("");
Trie file2=new Trie("");
if(args.length==0 || args[0]==null){
System.out.println("Please give a valid command file");
}
else{
try{
Scanner reader1 = new Scanner(new FileInputStream(args[2]));
Scanner reader2 = new Scanner(new FileInputStream(args[3]));
String d=args[0];
String n=args[1];
int depth=Integer.parseInt(d);
int numberOfStrings=Integer.parseInt(n);
while(reader1.hasNext());{
String[] ary=reader1.next().split("");
file1.insert(ary);
}
while(reader2.hasNext());{
String[] ary=reader1.next().split("");
file2.insert(ary);
}
reader1.close();
reader2.close();
System.out.print(file1);
System.out.print(file2);
}
catch(Exception e){
}
}
}
}
我认为插入操作是问题所在,文本文件只不过是随机字符串“dog god dog act cata asfdoh aosifdh oawrhi”