如何递归实现get()

问题描述 投票:0回答:1

我想知道我的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;
}
linked-list doubly-linked-list
1个回答
0
投票

这可能有帮助

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);        
}
© www.soinside.com 2019 - 2024. All rights reserved.