如何使用递归编写链接列表的包含方法? java的

时间:2013-09-21 02:46:48

标签: 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.getValue().equals(el))
        {
            return true;
        }
        else
        {
            next.contains(el);
        }

    }

2 个答案:

答案 0 :(得分:1)

public boolean contains(String el) {
   if (value.equals(el)) return true;
   if (next == null) return false;
   else return next.contains(el); 
}

答案 1 :(得分:0)

next.contains(el),只需在此之前添加一个return语句!

if (value.equals(el)) {
   return true;
}

return next.contains(el);

当然你必须处理next无效的时候(即你在最后一个元素),然后返回false。