欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

循环数组实现队列

程序员文章站 2024-03-18 11:52:16
...

队列是先进先出(FIFO)模式,从队尾加入元素的操作叫入队,从队首删除元素的操作叫出队;
设置两个指针分别为front指向队首,real指向队尾。开始时front和real分别为-1。当有元素入队时real+1;当有元素出队时front+1.

public class QueueSimulation<AnyType> {
	private static final int MAXSIZE = 20;
	private AnyType[] data;
	private int front;
	private int real;
	private int queuesize;

	public QueueSimulation() {
		initQueue();
	}

	@SuppressWarnings("unchecked")
	public void initQueue() {
		data = (AnyType[]) new Object[MAXSIZE];
		this.queuesize = 0;
		this.front = -1;
		this.real = -1;
	}

	public String intoQueue(AnyType element) {
		if((this.real+1)%MAXSIZE==this.front){
			return "队列已满";
		}else{
			this.real = (this.real+1)%MAXSIZE;
			this.data[real] = element;
			this.queuesize++;
			return element+"入队成功";
		}
	}

	public String outQueue() {
		if(this.front == this.real){
			return "队列为空";
		}else{
			this.front = (this.front+1)%MAXSIZE;
			this.queuesize--;
			return data[front]+"出队成功";
		}
	}
	public int size(){
		return this.queuesize;
	}
	public static void main(String[] args) {//测试函数
		QueueSimulation<String> qs = new QueueSimulation<>();
		String [] name = {"zhangsan","lisi","wangwu","zhaoliu","sunqi","chengba","dengjiu"};
		for(int i = 0 ;i<name.length;i++){
			System.out.println(qs.intoQueue(name[i]));
		}
		for(int i = 0;i<2;i++){
			System.out.println(qs.outQueue());
		}
		
	}
}

//输出结果为:
zhangsan入队成功
lisi入队成功
wangwu入队成功
zhaoliu入队成功
sunqi入队成功
chengba入队成功
dengjiu入队成功
zhangsan出队成功
lisi出队成功