我尝试过使用Java来实现教科书《算法导论》第三版中的算法,但没有太多成功。几乎每次我尝试实现它们时,我都会遇到许多错误,以至于我不确定作者自己是否尝试过实现他们自己的伪代码。但具体地说,在这种情况下,我遇到了Btree算法的问题。我认为问题出在B-Tree-Insert-Nonfull方法中。当我尝试运行程序时,这一行导致了一个空指针异常:
int i= x.totalKeys - 1;
然而,这没有任何意义。所有节点,比如本例中的x,在其构造函数中都被初始化为0,那么他的错误是如何发生的呢?我将把下面的函数封闭起来:
public void bTreeInsertNonfull(Node x, Integer k)
{
int i = x.totalKeys - 1;
if (x.leaf || (x.children[i] == null))
{
while( (i >= 0) && (k < x.keys[i]) )
{
x.keys[i+1] = x.keys[i];
i = i - 1;
}
x.keys[i+1] = k;
x.totalKeys = x.totalKeys + 1;
}
else
{
while ( (i >= 0) && x.keys[i] != null)
{
if (k < x.keys[i])
{
i = i - 1;
}
}
i = i + 1;
if ((x.children[i] != null) && (x.children[i].totalKeys == tUpper))
{
bTreeSplitChild( x, i, x.children[i] );
if (k > x.keys[i])
{
i = i + 1;
}
}
bTreeInsertNonfull(x.children[i], k);
}
}发布于 2012-10-19 17:07:42
详述Alex的想法:如果你看一下算法的最后一部分,有一行是这样说的:
if ((x.children[i] != null) && (x.children[i].totalKeys == tUpper))这暗示了x.children[i] == null是一种可能性。算法的最后一行调用bTreeInsertNonfull(x.children[i], k);,而不检查第一个参数是否为空。
https://stackoverflow.com/questions/12970733
复制相似问题