Java数据结构之堆和优先队列(4)

public class Main { public static void main(String[] args) { MaxHeap<Integer> maxHeap = new MaxHeap<>(); int[] nums = {90,80,70,60,50,60,20,10}; for (int i = 0; i < nums.length; i++) { maxHeap.add(nums[i]); } System.out.println("堆顶:" + maxHeap.findMax()); maxHeap.add(82);//添加82 System.out.println("取出堆顶值:" + maxHeap.extractMax()); System.out.println("堆顶:" + maxHeap.findMax());//是否为82 maxHeap.add(85);//添加85 System.out.println("堆顶:" + maxHeap.findMax()); //是否为85 System.out.println("测试结束"); } }

输出

堆顶:90 取出堆顶值:90 堆顶:82 堆顶:85 测试结束

用定义的最大堆去实现一个优先队列就变得十分简单了,优先队列本质上来说还是一个队列,用堆来实现队列的接口。

Queue接口类

public interface Queue<E> { int getSize(); boolean isEmpty(); void enqueue(E e); E dequeue(); E getFront(); }

优先队列(PriorityQueue类)

public class PriorityQueue<E extends Comparable<E>> implements Queue<E> { private MaxHeap<E> maxHeap; public PriorityQueue() { maxHeap = new MaxHeap<>(); } @Override public int getSize() { return maxHeap.size(); } @Override public boolean isEmpty() { return maxHeap.isEmpty(); } @Override public void enqueue(E e) { maxHeap.add(e); } @Override public E dequeue() { return maxHeap.extractMax(); } @Override public E getFront() { return maxHeap.findMax(); } }

实例

在股票市场,很多股民向股票代理打电话,股票代理公司优先处理vip客户(有钱¥)再处理普通的用户。把他们的money当做他们的优先程度

Customer类

public class Customer implements Comparable<Customer> { private int money; private String name; public Customer(int money, String name) { this.money = money; this.name = name; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int compareTo(Customer another) { if (this.money < another.money) { return -1; }else if (this.money > another.money) { return 1; }else { return 0; } } }

Main类

public class Main { public static void main(String[] args) { //优先队列使用示例 Queue<Customer> queue = new PriorityQueue<>(); Random random = new Random(); for (int i = 0; i < 10; i++) { int money = random.nextInt(1000000); queue.enqueue(new Customer(money,"客户" + i )); } while (true) { if (queue.isEmpty()) { break; } Customer customer = queue.dequeue(); System.out.println("优先处理 " + customer.getName() + " 因为他的money为:" + customer.getMoney() + "¥"); } } }

输出

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/dac0739a28da389db9e2cc4e1132777c.html