队列-java代码

public class QueueDemo {

    private int maxSize;
    private long[] queueArray;
    // 队列的头,实际是数组的尾
    private int header;
    // 队列的尾,实际是数组的头
    private int footer;
    private int nElems;
    
    public QueueDemo(int size){
        
        maxSize = size;
        queueArray = new long[maxSize];
        header = 0;
        footer = -1;
        nElems = 0;
    }
    // 插入队列,从队尾插入
    public void insert(long element){
        
        if(footer == (maxSize - 1)){
            footer = -1;
        }
        queueArray[++footer] = element;
        nElems++;
    }
    // 出队列,即取出数组尾
    public long remove(){
        
        long temp = queueArray[header];
        queueArray[header] = 0;
        if(++header == maxSize){
            header = 0;
        }
        nElems--;
        return temp;
    }
    // 取出队列头元素
    public long getHeader(){
        
        return queueArray[header];
    }
    // 取出队列数组
    public long[] getArray(){
        
        return queueArray;
    }
}

队列是先进先出,可以想象成火车进隧道

 

优先级队列:

import java.util.Arrays;

/**
 * 优先级数组
 * 
 * @author Orlion
 * @create 2015-09-12
 */
public class PriorityQDemo {

    private int maxSize;
    private long[] priorityqArray;
    private int header;
    private int footer;
    
    public PriorityQDemo(int size){
        
        maxSize = size;
        priorityqArray = new long[maxSize];
        header = 0;
        footer = -1;
    }
    // 插入优先级数组
    public void insert(long element){
        
        int i = footer;
        while(i > 0 && priorityqArray[i] > element){
            priorityqArray[i + 1] = priorityqArray[i];
            i--;
        }
        priorityqArray[i+1] = element;
        footer++;
    }
    // 出队列
    public long remove(){
        
        long temp = priorityqArray[header];
        priorityqArray[header] = 0;
        if(++header == maxSize){
            header = 0;
        }
        return temp;
    }
    // 打印队列
    public void getPriorityq(){
        System.out.print(Arrays.toString(priorityqArray));
    }
}

可以理解成有一定顺序的队列,也是先进先出

posted @ 2015-09-15 21:24  orlion  阅读(281)  评论(0编辑  收藏  举报