在java中使用递归方法
作为家庭作业,我被要求为自定义链表编写一个包含方法。 我知道递归方法应该有一个基本情况,然后是递归情况。但是,我在理解如何编写方法的递归情况时遇到了一些困难。到目前为止,这是我所写的,但是我的代码不止一次地执行基本情况。你能给我一些指导吗在java中使用递归方法,java,Java,作为家庭作业,我被要求为自定义链表编写一个包含方法。 我知道递归方法应该有一个基本情况,然后是递归情况。但是,我在理解如何编写方法的递归情况时遇到了一些困难。到目前为止,这是我所写的,但是我的代码不止一次地执行基本情况。你能给我一些指导吗 public class OrderedList { private Node first; //Constructor public OrderedList() { this.first = null; } //Return the numbe
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;
}
}
首先,我喜欢这样做:
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);
}
}
这会对用户隐藏实现细节,并在运行该方法时阻止覆盖列表。要实现递归解决方案,需要为
包含提供一个辅助方法。辅助方法应该有一个额外的参数,即节点
,从该节点开始测试。publiccontains
方法应该调用辅助方法并将this.first
作为开始节点传递。剩下的逻辑对您来说应该非常简单。从我看到的情况来看,一旦else statemnet执行一次,您的代码将返回true。我认为您需要做的是每次都将布尔值设置为false,因为递归的行为非常类似于while循环,如果不更新这些值,则会反复执行基本情况。为什么要更改该方法中的类变量?您应该使用传入的节点,而不是this.first
。每次调用该方法都会更改列表的顶部。你在破坏你的名单!是否有一种方法可以让我仅使用此方法保存列表?@user116061-可以编写辅助方法来不修改任何内容。我认为如果没有辅助方法,就无法编写递归的contains
方法。@TedHopp我认为唯一的方法是要求客户端使用类似list.contains(list.getFirst(),item)
的代码,这是不好的imo@thatidiotguy-我同意这样做没有好处。它还将改变公共接口,这可能意味着分配没有完成(即使该方法工作正常)。我有没有办法避免该方法重写列表而不必实现助手方法?@user116061不,这是标准方法。否则,您将不得不依赖代码的用户传入第一个节点,这将破坏封装。我的意思是你可以看到,我已经减少了你的代码量,所以我不知道你为什么要避开助手!