[英]stackoverflowerror on recursive method with arraylist
我在線程“主” java.lang.StackOverflowError中看到異常。 我希望知道下面的代碼出了什么問題。
public void addWord(String word){
addWord(word,root,0);
}
private void addWord(String word,Node root,int pos)
{
for(Node c:root.children)
{
if(word.charAt(pos)==c.letter)
{
addWord(word,c,pos++);
}
}
Node temp = new Node();
temp.letter=word.charAt(pos);
temp.children=new ArrayList<Node>();
root.children.add(temp);
if(pos==word.length()-1)
{
temp.terminus=true;
return;
}
if(pos<word.length()-1)
{
addWord(word,temp,pos++);
}
}
本質上,堆棧溢出來自以下事實:您的方法一直被遞歸調用,並且遞歸永遠不會結束。
一個可能的問題是此調用:
addWord(word,temp,pos++);
相當於
addWord(word,temp,pos);
pos = pos + 1;
您可能是說:
addWord(word,temp,++pos);
相當於
pos = pos + 1;
addWord(word,temp,pos);
我寫了一個簡單的addWord()
版本:
private void addWord(String word, Node aRoot, int pos) {
if (pos == word.length())
return;
for (Node c : aRoot.children) {
if (word.charAt(pos) == c.letter) {
addWord(word, c, pos+1);
return;
}
}
Node temp = new Node();
temp.letter = word.charAt(pos);
temp.children = new ArrayList<Node>();
temp.terminus = pos == word.length() - 1;
aRoot.children.add(temp);
addWord(word, temp, pos+1);
}
您代碼中的原始版本在基本情況和遞歸調用方面存在一些問題。 通常,應避免更改方法參數的值( pos++
部分)。
我猜想您正在構建Trie數據結構,並且我希望您在使用terminus
屬性時遇到問題。 想想看,如果您添加幾個帶有共同前綴的單詞,那將是終點節點? 您打算在同一級別添加多個具有相同letter
節點,還是要在同一級別共享具有相同字母的節點? 在后一種情況下, terminus
屬性的值是多少?
為了使我的觀點清晰明了,請繪制一個圖表,顯示執行以下代碼(密切注意每個節點中的terminus
值)后,Trie的外觀,並查看上面的實現是否提供了預期的結果。
Test t = new Test();
t.addWord("a");
t.addWord("abc");
t.addWord("ab");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.