在java中使用Recursive方法

时间:2013-07-22 18:15:25

标签: java

做作业我被要求为自定义链表编写一个包含方法。 我知道递归方法应该有一个基本情况,然后是递归情况。但是,我在理解如何编写方法的递归情况时遇到一些麻烦。到目前为止,这是我写的,但我的代码不止一次地执行基本情况。你能给我一些指导吗?

public class OrderedList {

private Node first;

//Constructor
public OrderedList() {
    this.first = null;
}

//Return the number of items in the list
public int size() {
    int counter = 0;
    Node pointer = this.first;
    while (pointer != null) {
        counter++;
        pointer = pointer.next;
    }
    return counter;
}

//Return an array of copies of the stored elements
public Comparable[] getStore() {

    Comparable[] elements = new Comparable[size()];
    Node pointer = this.first;
    if (this.first == null) {
        return elements;
    } else {
        int i = 0;
        while (pointer != null) {
            elements[i] = pointer.data;
            pointer = pointer.next;
            i++;
        }
        return elements;
    }

}
//true iff item matches a stored element
//Recursive

public boolean contains(Comparable item) {

    //Base case
    if (this.first == null) {

        return false;
    }
    Node pointer = this.first;
    this.first = this.first.next;

    if (pointer.data.compareTo(item) == 0) {

        return true;

    } 
    //Recursive case

    else {

        boolean info = contains(item);
        pointer.next = this.first;
        this.first = pointer;

        return info;
    }
}

3 个答案:

答案 0 :(得分:3)

首先,我喜欢这样做:

public boolean contains(Comparable item)
{
     return containsHelper(this.first, Comparable item);
}

private boolean containsHelper(Node node, Comparable item)
{
    //base case
    if(node == null)
    {   
         return false;
    }
    else
    {
         if(node.data.compareTo(item) == 0)
         {
             return true;
         }

         return containsHelper(node.next, item);
    }


}

这会隐藏用户的实现细节,并在您运行该方法时阻止列表被覆盖。

答案 1 :(得分:0)

要实现递归解决方案,您需要contains的辅助方法。辅助方法应该有一个额外的参数,即从Node开始测试。公共contains方法应调用辅助方法并将this.first作为起始节点传递。其余的逻辑应该非常简单,你可以弄明白。

答案 2 :(得分:0)

从我所看到的,一旦执行了一次else statemnet,你的代码将返回true。我认为你需要做的是每次都将boolean值设置为false,因为递归的行为非常类似于while循环,如果值没有更新,则基本情况会一遍又一遍地执行。

相关问题