单向队列
package com.shilei.dataStructure.array;
/**
* @author shilei
* @date 2020/4/7-22:47
*/
//数组实现的单项队列
public class ArrayQueue {
private int maxSize;//最大容量
private int front;//头指针
private int rear;//尾指针
private int[] array;
public ArrayQueue(int maxSize){
this.maxSize=maxSize;
this.array=new int[maxSize];
rear=0;
front=0;
}
//判断队列是否满
public boolean isFull(){
return rear == maxSize;
}
//判断队列是否为空
public boolean isEmpty(){
return rear == front;
}
public void put(int val){
if (isFull()){
throw new RuntimeException("队列已满 请不要添加了");
}
array[rear++]=val;
}
public int pop(){
if (isEmpty()){
throw new RuntimeException("队列为空 取不出数据");
}
int result = array[front];
front++;
return result;
}
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(3);
arrayQueue.put(1);
arrayQueue.put(2);
arrayQueue.put(3);
System.out.println(arrayQueue.pop());
System.out.println(arrayQueue.pop());
System.out.println(arrayQueue.pop());
System.out.println(arrayQueue.pop());
}
}
单项队列只能使用一次利用率太低 我们将它改进可以循环使用
package com.shilei.dataStructure.array;
/**
* @author shilei
* @date 2020/4/7-23:01
*/
public class CycleArrayQueue {
private int maxSize;
private int front;//指向下一个可读的位置
private int rear;//指向下一个可写的位置
private int[] array;
public CycleArrayQueue(int maxSize){
this.maxSize=maxSize;
this.array=new int[maxSize];
this.front=0;
this.rear=0;
}
//判断队列是否满
public boolean isFull(){
//TODO 重点在此
return (rear+1)%maxSize == front ;
}
//判断队列是否为空
public boolean isEmpty(){
return front == rear;
}
public void put(int val){
if (isFull()){
throw new RuntimeException("队列已满,请不要再添加了");
}
array[rear]=val;
//TODO 此处变化
rear = (rear+1)%maxSize;
}
//取出一个元素
public int pop(){
if (isEmpty()){
throw new RuntimeException("队列中没有数据了");
}
int result = array[front];
front = (rear +1)%maxSize;
return result;
}
//当前队列有多少元素
public int size(){
//TODO
return (rear + maxSize -front)%maxSize;
}
}