cho bài tập về nhà Tôi đã được yêu cầu viết một phương thức chứa cho một danh sách liên kết tùy chỉnh. Tôi biết rằng phương pháp đệ quy cần phải có một trường hợp cơ sở và sau đó là đệ quy case.Tuy nhiên, tôi gặp một số rắc rối sự hiểu biết làm thế nào để viết các trường hợp đệ quy của phương pháp. Cho đến nay đây là những gì tôi đã viết, nhưng mã của tôi là thực hiện các trường hợp cơ sở nhiều hơn một lần. Bạn có thể vui lòng cho tôi một số hướng dẫn không?Sử dụng phương pháp đệ quy trong 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;
}
}
Tại sao bạn thay đổi biến lớp trong phương thức đó? Bạn nên sử dụng một thông qua trong 'Node', không phải' this.first'. Bạn đang thay đổi đầu danh sách với mọi cuộc gọi của phương thức đó. Bạn đang phá hủy danh sách của bạn! – thatidiotguy