我目前的优先级队列存在问题。当我测试我的方法时,我得到一个错误,说我的队列没有返回最高优先级。我已经介入,我不明白为什么Poll或Offer方法导致了这个问题。任何帮助,将不胜感激。感谢
public class HeapArrayQueue <E extends Comparable<? super E> > extends AbstractQueue <E> {
@SuppressWarnings("unchecked")
private E[] data = (E[])(new Comparable[7]);
private int count = 0;
private int front = 0;
public int size() {
return count;
}
public boolean isEmpty() {
return size() == 0;
}
public E poll() {
if (isEmpty())
return null;
else {
E ans = data[front ];
front = (front+1);
return ans;
}
}
public boolean offer(E element) {
if (element == null)return false;
else {
ensureCapacity();
data[count] = element;
bubbleUpFromIndex(count);
count++;
return true;
}
}
private void bubbleUpFromIndex(int nodeIndex) {
if (nodeIndex != 0){
int parent = (nodeIndex -1) / 2;
if (data[nodeIndex].compareTo(data[parent]) > 0){
swap(nodeIndex, parent);
bubbleUpFromIndex(parent);
}
}
}
private void swap(int from, int to) {
E temp = data[from];
data[from] = data[to];
data[to] = temp;
}
private void ensureCapacity() {
if (count == data.length) {
@SuppressWarnings("unchecked")
E[] newData = (E[])new Comparable[data.length * 2];
for (int loop = 0; loop < count; loop++) {
newData[loop] = data[loop];
}
data = newData;
}
return;
}
public Iterator<E> iterator() {
return null;
}
}
测试失败
@Test
public void QueueRespectsPriority() {
nonEmptyQueue.offer(t1);
assertEquals("Queue should return element with highest priority", t1, nonEmptyQueue.poll());
}
答案 0 :(得分:1)
在vic上做comp103我接受了吗?看起来与我现在所做的非常相似。
我能看到的第一件事是你没有在民意调查中保留正确的优先权。这里(伪代码是我的方法)
public E poll(){
if (count = 0) return null
E item = root // We are returning the root node so store it as a var
root = end // place the end item in root position
end = null // set end item to null
count-- // subtract count
sinkDown(0) // Call sink down to restore ordering
return item // return item
}
答案 1 :(得分:0)
在bubbleUpFromIndex
方法中,您的大于号>
必须小于符号<
。你应该在另一个答案中使用poll方法,然后它就可以了。