3

文字列のリンク リストを返すメソッドを作成しようとしています。ツリーがあり、ツリー内の各ノードには文字が格納されています。メソッドは、ツリーを介してすべての可能なパスを見つけることになっています。各パスは、リストに追加される文字列を作成します。

2 番目の 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;
}
4

5 に答える 5

2

When you change s in the inner loop, you're just re-assigning the variable s, not the value stored in your linked list. Instead, you should loop through all the elements in your list updating them one by one. I think something like this should work:

//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
    int length = paths.size();
    for (int i=0; i<length; i++) {
        paths.offer(nodevalue + paths.poll());
    }
}

poll takes the first item from the front of the list, and offer puts the result on the back. You take the first item off, change it, then put it on the back—repeat paths.size() times and you end up with the updated items in the original order.

于 2012-11-15T06:35:09.703 に答える
1

文字列は不変型であり、代入

s = nodevalue + s;

認識されない

より良い解決策は

for (TreeNode t : childList){
    final List<String> pathes = t.findStrings();
    for (final String path : pathes) {
      // add all pathes to paths list adding nodevalue to the beginning
      paths.add(nodevalue + path); 
    }
}
于 2012-11-15T06:30:53.033 に答える
1

The enhanced for loop is not going to help here.

You are going to have to go with the traditional one as follows:

for (int i=0; i<paths.size(); i++){
    paths.set(i, paths.get(i) + paths.get(i));
}

Here: public E set(int index, E element)

于 2012-11-15T06:35:19.917 に答える
0

この声明では:

for (String s : paths){
            s = nodevalue + s;
}

実際には s の値を変更していません。実際、今のやり方ではできません。for-each ループは、反復する要素を変更できません。

于 2012-11-15T06:30:00.107 に答える
0

as Michael said you can't replace the values of an entry in a for each loop. And since Strings are immutable you can't change the existing string.

You'll need to perform a normal Loop:

for (int i=0;i<paths.size(); i++) {
    paths.set(i, nodevalue +paths.get(i));
}

Note that you don't change the value of the existing String but replace it with a new String at the same location.

于 2012-11-15T06:37:35.030 に答える