PriorityQueue是从JDK1.5开始提供的新的数据结构接口,它是一种基于优先级堆的极大优先级队列。
1、优先级队列是不同于先进先出队列的另一种队列。每次从队列中取出的是具有最高优先权的元素。
2、如果不提供Comparator的话,优先队列中元素默认按自然顺序排列,也就是数字默认是小的在队列头,字符串则按字典序排列(参阅 Comparable),也可以根据 Comparator 来指定,这取决于使用哪种构造方法。
3、优先级队列不允许 null 元素。
4、依靠自然排序的优先级队列还不允许插入不可比较的对象(这样做可能导致 ClassCastException)
链表实现优先队列
public class PriorityQueue {
private SortedList list = new SortedList();
//用于检索该队列的头部。但它不会将其删除。
public Object peek() throws Exception {
return list.findHead();
}
//插入指定的元素插入此优先级队列
public void offer(Object obj) {
list.insert(obj);
}
//用于检索并移除此队列的头,如果此队列为空,则返回null。
public Object poll() throws Exception {
return list.deleteHead();
}
public void display() {
list.display();
}
private class SortedList {
private class Node {
Node next;//下一个结点的引用
Object data;//结点元素
public Node(Object data) {
this.data = data;
}
}
private Node head;
public SortedList() {
head = null;
}
public void insert(Object obj){
Node node = new Node(obj);
Node pre = null;
Node cur = head;
//循环结束得到的cur结点的值是比要插入的大
while(cur != null &&
(Integer.valueOf(node.data.toString()) > Integer.valueOf(cur.data.toString()))){
pre = cur;
cur = cur.next;
}
if(pre == null)
head = node;
else
pre.next = node;
node.next = cur;
}
public Object findHead() throws Exception {
if(head == null)
throw new Exception("LinkedList is empty!");
return head.data;
}
public Object deleteHead() throws Exception {
if(head == null)
throw new Exception("LinkedList is empty!");
Node tempNode = head;
head = head.next;
return tempNode.data;
}
public void display(){
if(head == null)
System.out.println("empty");
Node cur = head;
while(cur != null){
System.out.print(cur.data.toString() + " -> ");
cur = cur.next;
}
System.out.print("\n");
}
}
}
测试
@Test
public void test3() throws Exception {
PriorityQueue p = new PriorityQueue();
p.offer(2);
p.offer(55);
p.offer(7);
p.display();
System.out.println(p.peek());
p.poll();
p.display();
}