我的堆实现中使用了两个迭代方法,一个名为%s
(用于入队),一个名为char answer[2]; // array of character
scanf( "%1s", answer ); // do not use & operator to obtain pointer, array
// expressions are converted to pointer expressions
// automatically in this case.
(用于出队)和一个名为reheapUp
的助手方法,用于操作reheapUp / reheapDown方法中使用的堆结构中的孔。
我试图制作reheapUp / reheapDown的递归版本,但我一直遇到各种各样的问题,即堆栈溢出。我尝试了不同的方法,但运气不好。以下是迭代版本,接下来是我最近尝试的递归reheapDown,名为reheapDown
:
newhole
最后:
recReheapdown
我的private void reheapUp(T element)
// Current lastIndex position is empty.
// Inserts element into the tree and ensures shape and order properties.
{
int hole = lastIndex;
while ((hole > 0) // hole is not root and element > hole's parent
&&
(element.compareTo(elements.get((hole - 1) / 2)) > 0))
{
// move hole's parent down and then move hole up
elements.set(hole,elements.get((hole - 1) / 2));
hole = (hole - 1) / 2;
}
elements.set(hole, element); // place element into final hole
}
private void reheapDown(T element)
// Current root position is "empty";
// Inserts element into the tree and ensures shape and order properties.
{
int hole = 0; // current index of hole
int newhole; // index where hole should move to
newhole = newHole(hole, element); // find next hole
while (newhole != hole)
{
elements.set(hole,elements.get(newhole)); // move element up
hole = newhole; // move hole down
newhole = newHole(hole, element); // find next hole
}
elements.set(hole, element); // fill in the final hole
}
类似,所以我不会发布它。如果有人能帮助我解决这个问题,我将非常感激。我在递归方面从来都不是很出色,但我正在尽我所能去学习。如果有人希望在编辑中看到private void recReheapDown(T element)
{
int hole = 0; // current index of hole
int newhole; // index where hold should move to
newhole = newHole(hole, element); //find next hole
if(newhole == hole)//base condition
{
elements.set(hole, element); //fill in the final hole
return;
}
elements.set(hole,elements.get(newhole));
hole = newhole; //move hole down
recReheapDown(element);
}
方法生效。
最后(仅仅因为我很好奇)迭代和递归版本之间的复杂性差异是什么?谢谢。
编辑:这是请求的newHole方法。
recReheapUp