定义: PriorityQueue<Integer> queue = new PriorityQueue<Integer>();

java中的优先队列默认从小到大

//自定义
//从大到小
import java.util.PriorityQueue;
import java.util.Scanner;
class node implements Comparable<node>{
int x;
    @Override
    public int compareTo(node o) {
        // TODO Auto-generated method stub
        return o.x-this.x;
    }
    
}
public class Main {
    static PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
    static PriorityQueue<node> q = new PriorityQueue<node>();
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        queue.offer(5);
        queue.offer(10);
        queue.offer(15);
        queue.offer(3);
        queue.offer(1);
        queue.offer(6);
        while(!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
        for(int i=1;i<=5;i++) {
            node xNode = new node();
            xNode.x = cin.nextInt();
            q.offer(xNode);
        }
        while(!q.isEmpty()) {
            System.out.println(q.poll().x);
        }
    }
}
posted on 2020-01-17 20:22  qdu_lkc  阅读(230)  评论(0编辑  收藏  举报