前言
使用数组实现循环队列,语言java
提示:以下是本篇文章正文内容,下面案例可供参考
一、循环队列
1.代码
代码如下(示例):
package com.review;
public class reviewQueen {
public static void main(String[] args) {
Queue queue = new Queue(5);
queue.push(1);
queue.push(2);
queue.push(5);
queue.push(3);
queue.push(3);
queue.show();
}
}
class Queue{
int maxSize;
int rear;
int front;
int arr[];
public Queue(int maxSize) {
this.maxSize = maxSize;
this.rear = 0;
this.front = 0;
arr = new int[maxSize];
}
public boolean isFull(){
return (rear + 1)%maxSize == front ? true : false;
}
public boolean isEmpty(){
return rear == front ? true : false;
}
public void push(int element){
if(isFull()){
System.out.println("队列满");
return;
}
arr[rear] = element;
rear = (rear + 1)%maxSize;
}
public void pop(){
if(isEmpty()){
System.out.println("队列空");
return;
}
System.out.println(arr[front]+"出队");
front = (front+1)%maxSize;
}
public void getHead(){
if (isEmpty()){
System.out.println("队列空");
}
System.out.println(arr[front]);
}
public void getFront(){
if(isEmpty()){
System.out.println("队列空");
}
System.out.println(arr[rear]);
}
public Integer getLength(){
return ( rear - front + maxSize)%maxSize;
}
public void show(){
if(isEmpty()){
System.out.println("队空");
return;
}
int len = getLength();
for (int i = front; i < (front+len); i++) {
System.out.print(arr[i]+"\t");
}
}
}
总结
以上是循环队列的总结
|