队列_优先级队列

优先级队列的队尾是不需要改变的,永远在低下标处。当队列增加数据时,队头的位置就是数据项的大小减去1.

 

public class PriorityQ {
    private long[] queArray;
    private int maxSize;
    private int nItem;
    public PriorityQ(int s) {
        maxSize=s;
        queArray=new long[maxSize];
        nItem=0;
    }
    //插入
    public void insert(long item) {
        int j;//要插入的位置
        if(nItem==0) {
            //如果一个数据项都没有,直接将item放入数组中
            queArray[nItem++]=item;
            
        }else {
            for(j=nItem-1;j>=0;j--) {
                //从队头开始寻找要插入的位置
                if(item>queArray[j])
                    queArray[j+1]=queArray[j];
                else
                    break;//找到位置
            }
            queArray[j+1]=item;
            nItem++;
            
        }
        
    }
    //删除
    public long remove() {
        return queArray[--nItem];
    }
    //获取队头的数据(也是数据项大小最小的)
    public long peekMin() {
        return queArray[nItem-1];
    }
    //判断是否为空
    public boolean isEmpty() {
        return nItem==0;
    }
    //判断是否是满的
    public boolean isFull() {
        return nItem==maxSize;
    }

}
public class Test {

    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()) {
            long item=thePQ.remove();
            System.out.print(item+" ");
        }

    }

}

 

posted @ 2017-12-22 10:41  S-Mustard  阅读(238)  评论(0编辑  收藏  举报