我正在尝试回答以下编程问题:
在heap.java程序中,该insert()方法在堆中插入一个新节点,并确保保留堆条件.编写一个toss()方法,将新节点放在堆数组中,而不尝试维护堆条件.(也许每个新项都可以简单地放在数组的末尾.)然后编写一个restoreHeap()方法来恢复整个堆中的堆状态.使用toss()多次,随后通过单个restoreHeap()比使用更有效的insert()反复当大量数据都必须在一个时间被插入.有关线索,请参阅heapsort的说明.要测试您的程序,请插入一些项目,再扔一些,然后还原堆.
我已经为折腾函数编写了代码,该函数在最后成功插入节点,并且不会修改堆条件.我遇到了这个restoreHeap功能的问题而我无法绕过它.我已经包含了以下两个功能.
heap.java的完整代码在这里(包括toss()和restoreHeap())
toss() - 我基于插入功能
public boolean toss(int key)
{
if(currentSize==maxSize)
return false;
Node newNode = new Node(key);
heapArray[currentSize] = newNode;
currentSize++;
return true;
} // end toss()
Run Code Online (Sandbox Code Playgroud)
restoreHeap() - 我基于trickleUp函数,我得到一个StackOverflowError.
public void restoreHeap(int index)
{
int parent = (index-1) / 2;
Node bottom = heapArray[index];
while( index > 0 &&
heapArray[parent].getKey() < bottom.getKey() )
{
heapArray[index] = …Run Code Online (Sandbox Code Playgroud) 我有一个字符串的ArrayList,我正在尝试删除ArrayList的奇数元素,即list.remove(1),list.remove(3),list.remove(5)等.
这是我试图使用的代码,它会引发IllegalStateException错误:
int i = 0;
for (Iterator<String> it = words.iterator(); it.hasNext(); )
{
if (i % 2 != 0 && it.hasNext())
{
it.remove();
}
i++;
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的(工作)方式来做到这一点?