【发布时间】:2015-03-05 06:06:43
【问题描述】:
下面是代码。数组索引表示小字符(a-z),索引为 26(英文字母的字符数)。它是一个单词字典,其中 children[character ascii value-97] 指向下一个节点。词尾给出 bool terminal=true。
所有函数都是递归的。在删除函数中,我们必须逐个字符地遍历到单词的末尾。遍历时,在第二次调用递归删除时,我丢失了所有引用并出现NullPointerException。
出现问题的代码行前面有注释。首先检查字典中是否存在单词。
import java.io.File;
import java.util.Scanner;
public class xxx {
public static void main(String[] args) {
Trie trie = new Trie();
if (trie.delete(word)) {
System.out.println("Word deleted");
} else {
System.out.println("Word not present");
}
break;
}
case "S": { //Search for the word
String word = tokens[1];
if (trie.isPresent(word)) {
System.out.println("Word found");
} else {
System.out.println("Word not found");
}
}
这个类只是调用 Node 类的递归函数。 trie 类从主类获取调用,然后将数据转移到 Node 类中的递归函数
class Trie {
Node root;
public Trie() {
root = new Node();
}
boolean isPresent(String s) { // returns true if s is present, false otherwise
current = root;
for (int i = 0; i < s.length(); i++) {
if (current.children[(int) s.charAt(i) - 97] == null) {
return false;
} else {
current = current.children[(int) s.charAt(i) - 97];
}
}
if (current.terminal == false) {
return false;
}
return true;
}
boolean delete(String s) { // returns false if s is not present, true otherwise
if (!isPresent(s)) {
return false;
}
root.delete(root,s);
return true;
}
int membership() { // returns the number of words in the data structure
return root.membership(root, 0);
}
void listAll() { // list all members of the Trie in alphabetical orber
root.listAll(root, "");
}
}
children[ascii value-97] 将引用一个节点,此链接将代表字母字符。 outDegree 将确保仅删除给定的字符串。该类具有所有递归函数。
class Node {
boolean terminal;
int outDegree;
Node[] children;
public Node() {
terminal = false;
outDegree = 0;
children = new Node[26];
}
public void delete(Node x, String s) {
if (s.length() > 1){
if(i<s.length())
delete(children[s.charAt(0)-97],s.substring(1)); //this is where problem occurs
}
else if(children[((int)s.charAt(0))-97].outDegree>0)
terminal =false;
else if(children[((int)s.charAt(0))-97].outDegree==0){
children[((int)s.charAt(0))-97]=null;
return;
}
if(children[s.charAt(0)-97].outDegree==0)
children[s.charAt(0)-97]=null;
}
}
【问题讨论】:
-
我知道 nullPointerExceptions 是如何发生的。我的代码适用于第一次递归,调试表明 children[] 数组中至少有一个非空项。
标签: java data-structures trie