循环队列
特性:先进先出,浪费一个数据单元,用来判断是否为满
原理
代码实现
class QueueLink{
int elem[];
/**
* 队头
*/
int front;
/**
* 队尾
*/
int rear;
/**
* 当前循环内部有效循环个数
*/
int usedSize = 0;
int allSize = 0;
/**
* 无参构造函数
*/
public QueueLink(){
this(10);
}
/**
* 有参构造函数
* @param size
*/
public QueueLink(int size){
this.elem = new int[size+1];
this.front = 0;
this.rear = 0;
this.allSize= size+1;
}
/**
* 判断是否为满
*/
public boolean isFull(){
if((this.rear+1)%this.allSize == this.front){
return true;
}
return false;
}
/**
* 入队
*/
public void push(int val){
if(isFull()){
return;
}
this.elem[this.rear] = val;
this.rear = (this.rear+1)%this.allSize;
this.usedSize++;
}
/**
* 判断是否为空
*/
public boolean isEmpty(){
return this.front == this.rear;
}
/**
* 出队
*/
public void pop(){
if(isEmpty()){
return;
}
this.elem[this.front] = -1;
this.front = (this.front+1)%this.allSize;
}
/**
* 得到队头元素
*/
public int getTop(){
if(isEmpty()){
return -1;
}
return this.elem[this.front];
}
/**
* 打印输出
*/
public void show(){
for(int i = this.front;i < this.rear;i = (i+1)%this.allSize){
System.out.print(this.elem[i]);
}
System.out.println();
}
}
/**
*
* @author jhl
*
*/
public class TestCQueueDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
QueueLink q1 = new QueueLink();
for (int i = 0; i < 10; i++) {
q1.push(i);
}
q1.show();
q1.pop();
q1.show();
int n = q1.getTop();
System.out.println(n);
}
}