PriorityQueue
此处步骤
1.建立一个内部结点(属性:数据域(data)和权重(weight))
2.建立这个结点的比较器myComparator(按照权重的大小设置优先级,权重小优先级大)
3.优先级队列中添加数据
4.按照权重越小优先级越高的原则输出数据
import java.util.Comparator;
import java.util.PriorityQueue;
public class PriorityQueueDemo {
static class N{
public int weight;
public int data;
public N(int weight,int data)
{
this.weight = weight;
this.data = data;
}
}
//建立一个N的比较器
static class myComparator implements Comparator<N>
{
@Override
public int compare(N n1, N n2) {
// TODO Auto-generated method stub
if(n1.weight<n2.weight)
{
return -1;
}else if(n1.weight>n2.weight)
{
return 1;
}
return 0;
}
}
public static void main(String[] args) {
//定义一个比较器
myComparator mc = new myComparator();
//将比较器传递给优先级队列
PriorityQueue<N> pq = new PriorityQueue<N>(10,mc);
//定义节点并插入到优先级队列中
N n1 = new N(1, 2);
N n2 = new N(2, 1);
N n3 = new N(3, 4);
N n4 = new N(4, 3);
pq.add(n1);
pq.add(n2);
pq.add(n3);
pq.add(n4);
/*
* 从优先级队列中按照权重由低到高的顺序输出输出数据
* 预期的结果是 2 1 4 3
*/
while(!pq.isEmpty())
{
System.out.print(pq.remove().data+" ");
}
}
}
输出结果:2 1 4 3