来自链表中方法的递归调用

时间:2014-02-04 20:08:22

标签: java recursion linked-list

public class Dene {

    private char ch;
    private Dene next;

    public Dene(char c) {
        this.ch = c;
    }

    public void add(Dene next) {
        this.next = next;
    }

    public boolean isWriteable(String s) {

        if (this.next == null) {
            if (s.contains(Character.toString(this.ch))) {
                return true;
            } else {
                return false;
            }
        } else {
            return this.next.isWriteable(s);
        }
    }
}


public static void main(String[] args) {
    Dene d = new Dene('a');
    Dene e = new Dene('e');
    Dene f = new Dene('f');
    d.add(e);
    e.add(f);
    System.out.println(d.IsWriteable("afb"));
}

IsWriteable获取一个字符串作为参数,并且如果可以从链接列表中连接的字符中写入该字符串,则可以递归地看到它。 但它没有用......有什么想法?

2 个答案:

答案 0 :(得分:2)

起初我有理解您的代码的问题。在我看来,你应该创建一个isWriteable(char c)函数,这样你就可以递归地检查一个字符:

public bool isWriteable(char c){
    if (this.x == null){
        return c == this.ch;
    else {
        return this.ch == c && this.x.isWriteable(c);
    }
}

要检查字符串,您只需检查字符串的每个字符。

更新

添加了字符检查代码:

public bool isWriteable(String s){
    char[] chars = s.toCharArray();
    int i;
    char c;
    for (i = 0; i < chars.length; i++){
        if (!isWriteable(c)){
            return false;
        }
    }
    return true;
}

(我希望这是正确的,因为我现在还没有使用Java一段时间)

更新的 我看到我可以让它变得如此简单:

public bool isWriteable(String s){
    if (this.x == null){
        return s.contains(this.ch);
    }
    else {
        return this.x.isWriteable(s) & s.contains(this.ch);
    }
}

这是递归的并且有其用途。

答案 1 :(得分:0)

看起来你缺乏开放和结束的大括号来清楚地定义每个if / else块中的内容。作为一般规则,即使Java不允许,您应该始终在if语句上设置一个开放和结束括号,并且循环使您的代码更易于阅读,跟踪和调试。

相关问题