优先队列Queue

Class:

package Heap;

import MyInterface.Comparator;
import MyInterface.Queue;
import java.util.NoSuchElementException;
import java.util.Arrays;

public class PriorityQueue<T> implements Queue<T> {

private T[] arr;
private int qSize;
private Comparator<T> comp;

public PriorityQueue() {
comp = new Greater<T>();
qSize = 0;
arr = (T[]) new Object[10];
}

public PriorityQueue(Comparator<T> comp) {
this.comp = comp;
qSize = 0;
arr = (T[]) new Object[10];
}

public boolean isEmpty() {
return qSize == 0;
}

public T peek() {
if(qSize == 0)
throw new NoSuchElementException("empty queue");

return arr[0];
}

public T pop() {
if(qSize == 0)
throw new NoSuchElementException("empty queue");

T top = Heaps.popHeap(arr, qSize, comp);
qSize--;
return top;
}

public void push(T item) {
if(qSize == arr.length)
enlargeCapacity();

Heaps.pushHeap(arr, qSize, item, comp);
qSize++;
}

private void enlargeCapacity() {
int newCapacity = 2 * arr.length;
T[] oldArr = arr;
arr = (T[])new Object[newCapacity];
for (int i = 0; i < qSize; i++)
arr[i] = oldArr[i];
oldArr = null;
}

public int size() {
return qSize;
}

public String toString() {
T[] tmpArr = (T[]) new Object[qSize];
for (int i = 0; i < qSize; i++)
tmpArr[i] = arr[i];
Heaps.heapSort(tmpArr, comp);
return Arrays.toString(tmpArr);
}

}



Test:

package Heap;

import MyInterface.*;

public class TestPriorityQueue {

public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Less<Integer>());
pq.push(new Integer(7));
pq.push(new Integer(1));
pq.push(new Integer(9));
pq.push(new Integer(0));
pq.push(new Integer(8));
pq.push(new Integer(2));
pq.push(new Integer(4));
pq.push(new Integer(3));
pq.push(new Integer(6));
pq.push(new Integer(5));

System.out.println(pq.peek()); // 9

System.out.println(pq); // [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

while(!pq.isEmpty())
System.out.print(pq.pop() + " "); // 0 1 2 3 4 5 6 7 8 9

}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值