【问题标题】:Java RecursiveLinkedList contains method [closed]Java RecursiveLinkedList 包含方法[关闭]
【发布时间】:2013-03-29 05:57:54
【问题描述】:

我正在做一个简单的linkedList类,这个类的要求之一是使用recurs来实现contains方法,add方法和remove方法。

基于示例,我发现我已经实现了 remove 方法,但是 contains 一直为我抛出错误。

谁能帮忙指出我的 contains 方法有什么问题,谢谢。

public class RecursiveLinkedList {

private int value;
private RecursiveLinkedList next;

/*
 * Default Constructor
 * 
 * @param value an absolute int value for the current Node
 * @param next an absolute RecursiveLinkedList value for the current Node
 */
public RecursiveLinkedList(int value, RecursiveLinkedList next) {
    this.value = value;
    this.next = next;
}

/*
 * Constructor Empty, when user supplies an empty for the construcot use 
 * value = - 1 and next = null as input parameters
 * 
 * @param value an absolute int value for the current Node
 * @param next an absolute RecursiveLinkedList value for the current Node
 */
public static final RecursiveLinkedList EMPTY = new RecursiveLinkedList(-1, null) 
{
    public RecursiveLinkedList remove(int n) { return this; };

    public String toString() { return ""; };
};

public RecursiveLinkedList remove(int n) {
    if (value == n){
        return next;
    }
    //Call the remove method of the next Node if the selected Node is not the current node
    return new RecursiveLinkedList(value, next.remove(n));
}

public boolean contains(int n) {
    if (value == n){
        return true;
    }else if(next == null){
        return false;
    }
    return new RecursiveLinkedList(value, next).contains(n);
} 

public String toString() {
    return value + "," + next.toString();
}

public static void main(String[] args) {
    RecursiveLinkedList l = new RecursiveLinkedList(1,
                    new RecursiveLinkedList(2, 
                    new RecursiveLinkedList(2,
                    new RecursiveLinkedList(3, 
                    new RecursiveLinkedList(4, EMPTY)))));
    System.out.println(" Test to String Method : " + l.toString());
    System.out.println(" Test remove method " + l.remove(1).toString());
    System.out.println(" Test contains method " + String.valueOf(l.contains(4)));
}

}

【问题讨论】:

  • 回复:“包含不断为我抛出错误”:你看过错误吗?你从中学到了什么? (这是什么类型的错误?消息是什么?它发生在哪一行?)
  • 为什么每次返回都创建一个新的链表?
  • 感谢 cmets,它在第 45 行抛出错误,我在创建新实例而不是直接调用下一个对象时犯了错误。

标签: java recursion contains singly-linked-list


【解决方案1】:

为了防止 StackOverflowError 你应该改用:

public boolean contains(int n) {
    if (value == n){
        return true;
    }else if(next == null){
        return false;
    }
    return next.contains(n);
}

【讨论】:

  • 非常感谢您指出,是的,我不应该创建新实例。谢谢和问候
猜你喜欢
  • 1970-01-01
  • 2014-01-31
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-26
  • 1970-01-01
  • 2011-08-31
相关资源
最近更新 更多