사용자 지정 연결 목록에 대해 contains 메서드를 작성하라는 요청을 받았습니다. 저는 재귀 적 메소드가 기본 케이스와 재귀 케이스를 가져야한다는 것을 알고 있습니다. 그러나 메소드의 재귀 적 케이스를 작성하는 방법을 이해하는 데 어려움을 겪고 있습니다. 지금까지 내가 작성한 내용이지만 내 코드는 기본 사례를 두 번 이상 실행합니다. 지도 좀 해줄 수있어?숙제에 대한 자바의 재귀 메서드 사용
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;
}
}
왜 메소드에서 클래스 변수를 변경하고 있습니까? 'this.first'가 아니라'Node'에 전달 된 것을 사용해야합니다. 해당 메소드를 호출 할 때마다 목록의 맨 위가 변경됩니다. 당신은 당신의 명부를 파괴하고 있습니다! – thatidiotguy