作業我被要求爲自定義鏈表編寫一個包含方法。 我知道遞歸方法應該有一個基本情況,然後是遞歸情況。但是,我在理解如何編寫方法的遞歸情況時遇到了一些麻煩。到目前爲止,這是我寫的,但我的代碼不止一次地執行基本情況。你能給我一些指導嗎?在java中使用遞歸方法
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;
}
}
你爲什麼要改變該方法中的類變量?你應該使用傳入的'Node',而不是'this.first'。每次調用該方法時都會更改列表的頂部。你正在銷燬你的名單! – thatidiotguy