• 用数组实现的优先级队列


    public class PriorityQ {
        private int maxSize;
        private long[] queArray;
        private int nItems;
        
        //constructor
        public PriorityQ(int s){
            maxSize = s;
            queArray = new long[maxSize];
            nItems = 0;
        }
        
        //insert
        public void insert(long item){
            int j;
            if(nItems == 0)
                queArray[nItems++] = item;
            else{
                for(j=nItems-1; j>=0; j--){
                    if(item > queArray[j])
                        queArray[j+1] = queArray[j]; 
                    else
                        break;
                    
                }//end for
                queArray[j+1] = item;
                nItems++;
            }//end else
        }
        
        public long remove(){
            return queArray[--nItems];
        }
        
        public long peekMin(){
            return queArray[nItems - 1];
        }
        
        public long peekMax(){
            return queArray[0];
        }
        
        public boolean isEmpty(){
            return nItems == 0;
        }
        
        public boolean isFull(){
            return nItems == maxSize;
        }
    }
    public class PriorityQApp {
        public static void main(String[] args) {
            PriorityQ thePQ = new PriorityQ(5);
            thePQ.insert(30);
            thePQ.insert(50);
            thePQ.insert(10);
            thePQ.insert(40);
            thePQ.insert(20);
            
            while(!thePQ.isEmpty()){
                System.out.println(thePQ.remove());
            }
        }
    }

    优先级队列

      优先级队列是比栈和队列更专用的数据结构。但他在很多情况下都很有用。像普通队列一样,优先级队列有一个队头和一个队尾,并且也是从对头移除数据项。不过在优先级队列中,数据项按关键字的值有序,这样关键字最小数据项(或者在某些实现中是关键字最大的数据项)总在队头。数据项插入的时候会按照顺序插入到合适的位置以确保队列的顺序。

  • 相关阅读:
    定义一个动态的二维数组?
    学习STL map, STL set之数据结构基础
    CMM
    详细解说STL string
    仔细选择你的容器
    C++字符串类string简析
    流氓软件及反流氓软件的技术分析
    标准C++的类型转换符:static_cast、dynamic_cast、reinterpret_cast和const_cast
    C++资料下载
    unix系统操作命令大全
  • 原文地址:https://www.cnblogs.com/yony/p/2877880.html
Copyright © 2020-2023  润新知