Java递归函数有时工作

时间:2018-03-11 22:27:06

标签: java recursion stack-overflow

我已经调用了迄今为止所学到的东西,仍然无法解决这个问题所以决定来这里。

BasicBlock对象由整数引用,并保存对列表中更多块的“地址”的引用。我想获取他们所持有的地址,我想以递归的方式做到这一点。一个BasicBlock可以保存对0个或更多其他块的引用。

下面的递归函数getFunctionReferences不断返回堆栈溢出错误,但有时会设法工作。

Map<Integer,BasicBlock> blockList blockList = new TreeMap<Integer,BasicBlock>();

public HashSet<Integer> getAssociatedAddresses(int function) {
    HashSet<Integer> blockAddresses = new HashSet<Integer>();   
    getFunctionReferences(this.blockList.get(function),blockAddresses);
    return blockAddresses;
}

private void getFunctionReferences(BasicBlock block, HashSet<Integer> blockAddresses){ 
    for (int x : block.getAddressReferenceList()) {  
        blockAddresses.add(x);
        getFunctionReferences(this.blockList.get(x), blockAddresses);
    }
}

我知道我这次通话有问题,特别是因为没有基本情况。但是当我在这样的循环中时,我不知道如何处理递归....我也不知道合适的基本情况。

得到大力赞赏。

由于

1 个答案:

答案 0 :(得分:2)

如果你有循环(例如块1引用块2引用块3引用块1),你将获得无限递归,导致StackOverflowError

为避免这种情况,您可以利用您维护的HashSet个访问过的块。您可以简单地检查是否已访问过某个块,并避免再次进行递归调用:

private void getFunctionReferences(BasicBlock block, HashSet<Integer> blockAddresses){ 
    for (int x : block.getAddressReferenceList()) {  
        if (blockAddresses.add(x)) { // only make a recursive call if x wasn't already
                                     // in the Set
            getFunctionReferences(this.blockList.get(x), blockAddresses);
        }
    }
}
相关问题