Java 如何递归实现get()
我想知道我的get方法有什么错。在使用循环之前,我已经做过这项工作,但使用递归似乎无法达到同样的效果。我的size()方法适用于递归,但我很困惑为什么我似乎无法让get()工作。有没有人能给我一些指示,告诉我哪里出了问题,或者我只是混淆了代码的位置Java 如何递归实现get(),java,recursion,linked-list,nodes,doubly-linked-list,Java,Recursion,Linked List,Nodes,Doubly Linked List,我想知道我的get方法有什么错。在使用循环之前,我已经做过这项工作,但使用递归似乎无法达到同样的效果。我的size()方法适用于递归,但我很困惑为什么我似乎无法让get()工作。有没有人能给我一些指示,告诉我哪里出了问题,或者我只是混淆了代码的位置 public class Node { public Node previous; public Node next; public int size() { int count = 0; if (nex
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;
}
公共类节点{
公共节点前向;
公共节点下一步;
公共整数大小(){
整数计数=0;
if(next==null){
计数+=1;
}
如果(下一步!=null){
count=1+next.size();
}
返回计数;
}
公共节点get(int idx){
整数计数=0;
如果(下一步!=null){
如果(idx>=0&&idx,这可能会有所帮助
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);
}
public节点获取(int索引){
如果(指数<0){
//询问负索引。抛出异常或返回null
}
如果(index==0){返回此;}
if(next==null){
//索引超出范围。引发异常或返回null
}
返回next.get(索引-1);
}
你可以像我用我的单元格类那样做。
每次递增计数器
并再次调用get(idx)
时,计数器
将重置为0
。这是因为在堆栈
中发生递归,并且只有一个变量名为计数器
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
}
}
public Cell get(int index)抛出IndexOutOfBoundsException{
如果(索引<0 | |索引>=size()){//索引已失效
抛出新的IndexOutOfBoundsException();
}否则{
innerGet(索引);
}
}
公共单元格innerGet(int索引){
如果(index==0){//这个元素应该是零
归还这个;
}否则{
返回next.innerGet(--index);//减少索引
}
}
如果每次递归调用innerGet(index)
时递减索引
,它就会起作用。这就像递增计数器一样,但相反。
我实现了innerGet(int-index)
,因为如果递归调用get(int-index)
,由于size()
方法,它有一个O(n^2)。如果这样实现它,它就是O(n)