簡體   English   中英

刪除特里字時出現NullPointerException

[英]NullPointerException when deleting a trie word

下面是代碼。 數組索引表示小字符(az),索引是26(英文字母表中的字符數)。 它是一個單詞詞典,其中子項[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, "");

}

}

子項[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;
    }

}

您的問題不在您評論的代碼行中。 您的問題是如何初始化數組:

children = new Node[26];

這行代碼分配數組的內存。 然而,陣列的每個元素的值被設置為NULL為對象的引用,對Unicode NULL字符char的原語, falseboolean元,以及0為數字原語。 如果要使其正常工作,則必須正確初始化陣列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM