【问题标题】:How to implement get() recursively如何递归实现get()
【发布时间】:2020-06-06 03:35:03
【问题描述】:
我想知道我的 get 方法做错了什么。我在使用循环之前已经这样做了,但我似乎无法使用递归得到相同的结果。我的 size() 方法适用于递归,但我很困惑为什么我似乎无法让 get() 工作。有人可以给我任何错误的指示,或者我只是混淆了代码的位置。
public class Node {
public Node previous;
public Node next;
public int size() {
int count = 0;
if (next == null) {
count += 1;
}
if (next != null) {
count = 1 + next.size();
}
return count;
}
public Node get(int idx) {
int count = 0;
if (next != null) {
if (idx >= 0 && idx <= size()) {
if (count == idx) {
return next.previous;
}
count++;
}
//return get(idx);
}
return next.previous;
}
【问题讨论】:
标签:
java
recursion
linked-list
nodes
doubly-linked-list
【解决方案1】:
这可能会有所帮助
public Node get(int index) {
if (index < 0) {
// Asked negative index. Throw exception or return null
}
if (index == 0) { return this; }
if (next == null) {
// Index out of bounds. Throw exception or return null
}
return next.get(index - 1);
}
【解决方案2】:
您可以像我使用 Cell<T> class 那样做。
每次您increment counter 然后再次调用get(idx) 时,counter 将被重置为0。这是因为Stack 中发生了递归,并且只有一个变量称为counter。
public Cell<T> get(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= size()) { // index is out of bonds
throw new IndexOutOfBoundsException();
} else {
innerGet(index);
}
}
public Cell<T> innerGet(int index) {
if (index == 0) { // this element is supposed to be zero
return this;
} else {
return next.innerGet(--index); // decrement the index
}
}
如果你 decrement index 每次递归调用 innerGet(index),它就可以工作。这就像增加一个计数器,但反过来。
我实现了innerGet(int index),因为如果您递归调用get(int index),由于size() 方法,这有一个O(n^2)。如果以这种方式实现,则为 O(n)。