我試圖創建一個返回字符串鏈表的方法。有一棵樹,樹中的每個節點都存儲一個字符。該方法應該可以找到樹中所有可能的路徑。每個路徑都會創建一個字符串,並將其添加到列表中。遍歷列表中添加字符到Java中的字符串列表
在第二個for循環中似乎存在一個問題,我無法弄清楚。該方法只返回在第一個if語句中添加的字符。
每個節點都包含變量childList(它是子節點的鏈表)和nodevalue(它是節點正在存儲的字符)。
public LinkedList<String> findStrings() {
LinkedList<String> paths = new LinkedList<String>();
//add character to list if there are no children
if (childList.isEmpty()){
paths.add("" + nodevalue);
return paths;
}
//use recursion to add paths from all children to the list
for (TreeNode t : childList){
paths.addAll(t.findStrings());
//add nodevalue to the beginning of all strings in the list
for (String s : paths){
s = nodevalue + s;
}
}
for (String s : paths) System.out.println(s); //for debugging
return paths;
}
或者,使用['ListIterator'](http://docs.oracle.com/javase/6/docs/api/java/util/ListIterator.html)在迭代時更新值也可以很好地工作。 – DaoWen