JAVA数据结构之循环队列的实现

时间:2021-11-24 17:37:57

1、循环队列CircleQueue类的实现代码如下所示:

public class CircleQueue {
private Object[] array;
private int capacity;//队列容量
private int count;//队列中元素的个数
private int front;
private int rear;

public CircleQueue(int capacity){
this.capacity = capacity;
array = new Object[capacity];
count = 0;
front = 0;
rear = 0;
}

//入队
public boolean append(Object data){
boolean ret = (array != null) && (capacity > 0);

if(ret){
array[rear] = data;
rear = (rear + 1) % capacity;

count++;

if(count > capacity){
count = capacity;
}
}

return ret;
}

//出队
public Object retrieve(){
Object data = null;

if((array != null) && (capacity > 0) && (count > 0)){
data = array[front];
array[front] = null;
front = (front + 1) % capacity;
count--;
}

return data;
}

//获取队列中元素的个数
public int getCount(){
return count;
}

//获取队列的容量
public int getCapacity(){
return capacity;
}

//查看队头的数据,只查看,不删除。
public Object getHead(){
Object ret = null;

if(array != null && capacity > 0 && count > 0){
ret = array[front];
}

return ret;
}

public boolean isEmpty(){
return count == 0;
}

//清空队列中的元素
public void clear(){
array = null;
array = new Object[capacity];
count = 0;
front = 0;
rear = 0;
}

public void destroy(){
array = null;
count = 0;
front = 0;
rear = 0;
}
}
2、测试类Test的实现代码如下所示:

public class Test {

public static void main(String[] args) {
CircleQueue queue = new CircleQueue(5);
queue.append("元素1");
queue.append("元素2");
queue.append("元素3");
queue.append("元素4");
queue.append("元素5");
queue.append("元素6");
queue.append("元素7");

System.out.println("队列的容量:"+queue.getCapacity());
System.out.println("队列中元素的个数:"+queue.getCount());
System.out.println("队列是否为空?"+queue.isEmpty());
System.out.println("队头元素:"+queue.getHead());
System.out.println("出队:");

while(!queue.isEmpty()){
System.out.print(queue.retrieve()+" ");
}

queue.clear();
System.out.println("\n\n队列的容量:"+queue.getCapacity());
System.out.println("队列中元素的个数:"+queue.getCount());
System.out.println("队列是否为空?"+queue.isEmpty());

queue.destroy();
}
}