队列跟栈一样,只能访问单个元素,但相较于栈的LIFO(后进先出),则表现为FIFO(先进先出),它总是最先移除先进入队列的元素,即队头元素。
循环队列
public class Queue {
private int maxSize;
private long[] queueArray;
private int start;
private int end;
private int items;
public Queue(int size){
this.maxSize = size;
this.queueArray = new long[maxSize];
this.start = 0;
this.end = -1;
this.items = 0;
}
/**
* 插入操作,从队尾插入,如果队列已满,则将end置为-1
* 时间复杂度 O(1)
* @param i
*/
public void insert(long i) throws Exception{
if(isFull()){
throw new Exception("栈已满!");
}
//如果 队尾下标为maxSize-1,则将下标置为-1
if(end == maxSize-1){
end = -1;
}
queueArray[++end] = i;
items++;
}
/**
* 移除操作,从队头移除。
* 时间复杂度 O(1)
* @return
*/
public long remove() throws Exception{
if(isEmpty()){
throw new Exception("栈为空!");
}
long temp = queueArray[start++];
if(start == maxSize){
start = 0;
}
items--;
return temp;
}
/**
* 队头元素
* @return
*/
public long peekFront(){
return queueArray[start];
}
/**
* 队列是否为空
* @return
*/
public boolean isEmpty(){
return (items == 0);
}
/**
* 队列是否已满
* @return
*/
public boolean isFull(){
return items == maxSize;
}
}
向队列中插入几个元素,然后打印移除的元素:
public class QueueTest {
public static void main(String[] args) throws Exception{
Queue queue = new Queue(5);
queue.insert(0);
queue.insert(1);
queue.insert(2);
queue.insert(3);
queue.insert(4);
queue.remove();
queue.remove();
while(!queue.isEmpty()){
System.out.println(queue.remove());
}
}
打印结果如下:
可以看到,最先加入队列的元素先打印。
优先级队列
/**
* 优先级队列
* 元素按大小顺序排列的队列,小的在队头,大的在队尾
* @author sunyan
*
*/
public class PriorityQueue {
private int maxSize;
private long[] queueArray;
private int items;
public PriorityQueue(int size){
this.maxSize = size;
this.queueArray = new long[maxSize];
this.items = 0;
}
public void insert(long i){
int j;
if(items == 0){
queueArray[items++] = i;
}else{
for(j=items-1;j>=0;j--){
if(i > queueArray[j]){
queueArray[j+1] = queueArray[j];
}else{
break;
}
}
queueArray[j+1] = i;
items ++;
}
}
public long remove(){
return queueArray[--items];
}
public long peekMin(){
return queueArray[items-1];
}
public boolean isEmpty(){
return items==0;
}
public boolean isFull(){
return items==maxSize;
}
}
public class QueueTest {
public static void main(String[] args) throws Exception{
PriorityQueue priorityQueue = new PriorityQueue(5);
priorityQueue.insert(5);
priorityQueue.insert(3);
priorityQueue.insert(4);
priorityQueue.insert(1);
priorityQueue.insert(8);
System.out.println(priorityQueue.remove());
}
}
打印如下
可以看到优先级队列按照从小到大的顺序输出。