在java中使用Recursive方法
发布时间:2020-05-25 22:37:45 所属栏目:Java 来源:互联网
导读:对于家庭作业,我被要求为自定义链表编写一个包含方法. 我知道递归方法应该有一个基本情况,然后是递归情况.但是,我在理解如何编写方法的递归情况时遇到一些麻烦.到目前为止,这是我写的,但我的代码不止一次地执行基本情况.你能给我一些指导吗? public class Or
|
对于家庭作业,我被要求为自定义链表编写一个包含方法.
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);
}
}
这会隐藏用户的实现细节,并在运行该方法时阻止列表被覆盖. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
