1:基于简单循环数组实现队列
public class Queue {
private int [] queArray;
private int maxSize;
public int front; //存储队头元素的下标
public int rear; //存储队尾元素的下标
public static int length; //队列元素个数
//构造方法,初始化队列
public Queue(int maxSize){
this.maxSize = maxSize;
queArray = new int[maxSize];
front = 0;
rear = -1;
length = 0;
}
//插入
public void insert(int elem) throws Exception{
if(isFull()){
throw new Exception("队列已满,不能进行插入操作!");
}
//如果队尾指针已到达数组的末端,插入到数组的第一个位置
if(rear == maxSize-1){
rear = -1;
}
queArray[++rear] = elem;
length++;
}
//删除
public int remove() throws Exception{
if(isEmpty()){
throw new Exception("队列为空,不能进行移除操作!");
}
//如果队头指针已到达数组末端,则移到数组第一个位置
if(front == maxSize){
front = 0;
}
int item = queArray[front++];
length--;
return item;
}
//查看队头元素
public int peek() throws Exception{
if(isEmpty()){
throw new Exception("队列内没有元素!");
}
return queArray[front];
}
//获取队列长度
public int size(){
return length;
}
//判空
public boolean isEmpty(){
return (length == 0);
}
//判满
public boolean isFull(){
return (length == maxSize);
}
public static void main(String[] args) throws Exception{
Queue que = new Queue(10);
que.insert(1);
que.insert(2);
que.insert(3);
que.insert(4);
que.insert(5);
que.insert(6);
System.out.println(que.peek());
System.out.println(length);
System.out.println(que.remove());
System.out.println(que.peek());
}
}
运行结果:
1
6
1
2
2:基于动态循环数组实现队列
//基于动态循环数组实现队列
public class Queue {
public int[] queArray;
public static int length;//数组中元素的个数
public int maxsize;
public int rear;//队尾元素的下标
public int front;//队首元素的下标
//通过构造方法实现对队列的初始化
public Queue(int maxsize){
this.maxsize = maxsize;
queArray = new int[maxsize];
length = 0;
rear = -1;
front = 0;
}
//插入
public int insert(int item){
if(isFull()){
doubleArray();
}
if(rear == maxsize-1){
rear = -1;
}
queArray[++rear] = item;
length++;
return item;
}
public void doubleArray(){
int[] newArray = new int[maxsize*2];
for(int i = 0;i<maxsize;i++){
newArray[i] = queArray[i];
}
maxsize = maxsize*2;
queArray = newArray;
}
//删除
public int delete() throws Exception{
if(isEmpty()){
throw new Exception("队列为空,不能执行删除操作");
}
if(front == maxsize){
front = 0;
}
int elem = queArray[front++];
length--;
return elem;
}
//判空
public boolean isEmpty(){
return (length == 0);
}
//判满
public boolean isFull(){
return (length == maxsize);
}
//查看队头元素
public int seek() throws Exception{
if(isEmpty()){
throw new Exception("队列为空,不能查看队头元素");
}
return queArray[front];
}
public static void main(String[] args) throws Exception{
Queue que = new Queue(5);
que.insert(1);
que.insert(2);
que.insert(4);
que.insert(5);
que.insert(6);
que.insert(8);
que.insert(10);
System.out.println(que.seek());
System.out.println(length);
que.delete();
System.out.println(length);
}
}
运行结果:
1
7
6