对于作业,我被告知要编写自定义链表的插入方法(按顺序)。我写了基本案例,但我仍然不明白递归案例。我知道我刚刚问过如何编写 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) {
return containsHelper(this.first, 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);
}
}
//Add item preserving the order of the elements
//Recursive
public void insert(Comparable item) {
insertHelper(this.first, item);
}
public void insertHelper(Node pointer, Comparable item) {
//Base case
Node store = new Node(item);
if (pointer == null) {
store.next = this.first;
this.first = store;
return;
}
if (pointer.data.compareTo(item) > 0 ) {
store.next = pointer;
return;
}
if (pointer.data.compareTo(item) < 0 && pointer.next == null) {
store.next = pointer.next;
pointer.next = store;
return;
} else {
Node save = this.first;
this.first = this.first.next;
insertHelper(this.first, item);
if (pointer.data.compareTo(item) > 0) {
save.next = store;
this.first = save;
} else {
save.next = pointer;
this.first = save;
}
}
}