优先队列的实现

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
		
	}

}

你可能感兴趣的:(java)