Java数据结构----优先队列

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();
    }





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值