如何使用递归编写链表的contains方法?JAVA
我需要使用递归编写一个contains方法,这意味着查找其中一个节点中是否存在“element”如何使用递归编写链表的contains方法?JAVA,java,methods,recursion,linked-list,Java,Methods,Recursion,Linked List,我需要使用递归编写一个contains方法,这意味着查找其中一个节点中是否存在“element” public class SortedSetNode implements Set { protected String value; protected SortedSetNode next; } public boolean contains(String el) { if (next.get
public class SortedSetNode implements Set
{
protected String value;
protected SortedSetNode next;
}
public boolean contains(String el) {
if (next.getValue().equals(el))
{
return true;
}
else
{
next.contains(el);
}
}
好的下一步。包含(el)
,只需在前面添加一个return语句
if (value.equals(el)) {
return true;
}
return next.contains(el);
当然,您必须处理
next
无效时(即您位于最后一个元素),然后返回false。如果next
为null(未找到字符串),它将抛出NullPointerException,这就是为什么我的答案中有最后一句:)我已更正为:公共布尔包含(字符串el){
if(next!=null)
{return false;}else if(next.getValue().equals(el)){return true;}else{return next.contains(el);}
不起作用。if(next!=null){return false;}
意味着如果有下一个元素,你将返回false。试着像人一样思考你将如何做,把基本步骤和顺序写在纸上,然后转换成代码。或者阿尔法辛的代码也可以返回false
而不是dalse
@Smac89-他可能已经将dalse
定义为常量:-)@StephenC ah True是的。但是常量应该大写?您可能需要重写contains
方法,因为您的类实现了java.util.set
,并且该类也有一个contains
方法。在该上下文中使用递归是一个奇怪的要求:如果列表足够大,并且项接近尾端,您将设置一个StackOverflower错误(10k元素应足以将其破坏)。。。
public boolean contains(String el) {
if (value.equals(el)) return true;
if (next == null) return false;
else return next.contains(el);
}