我正在研究一个简单的linkedList类,这个类的要求之一是使用recurs来实现contains方法、add方法和remove方法。
根据示例,我发现我已经实现了 remove 方法,但是 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)));
}
}