gpt4 book ai didi

java - 在java中使用递归方法

转载 作者:搜寻专家 更新时间:2023-10-31 20:21:03 25 4
gpt4 key购买 nike

家庭作业要求我为自定义链表编写包含方法。我知道递归方法应该有一个基本案例,然后是递归案例。但是,我在理解如何编写该方法的递归案例时遇到了一些麻烦。到目前为止,这就是我所写的内容,但我的代码不止一次执行基本案例。你能给我一些指导吗?

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);
}


}

这对用户隐藏了实现细节,并且在您运行该方法时阻止您的列表被覆盖。

关于java - 在java中使用递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17794525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com