用简单数组实现队列(java)

队列特性,先进先出,FIFO

属性:array,front,size

方法:入队列,出队列,是否为空,大小,返回顶端元素

其中循环队列,rear = (front + size) % array.length

front = (front + 1) % array.length

public class MyArrayQueue {
	int[] array;
	int size;
	int front;
	int rear;
	public MyArrayQueue(int len) 
	{
		array = new int[len];
		size = 0;
		front = 0;
		rear = 0;
	}
	public boolean isEmpty() 
	{
		if (size ==0) 
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
	public int top() 
	{
		int ret = 0;
		ret = array[front];
		return ret;
	}
	public void enqueue(int key) throws Exception
	{
		if (size < array.length) 
		{		
			rear = (size + front) % array.length;
			array[rear] = key;
			size = size + 1 ;
		}
		else 
		{
			throw new Exception("The queue is full!");
		}
	}
	public int dequeue() throws Exception
	{
		if (size > 0) 
		{
			int ret = array[front];
			array[front] = 0;		
			front = (front + 1)% array.length;
			size = size - 1 ;
			return ret;
		}
		else 
		{
			throw new Exception("The queue is empty!");
		}
	}
	public void print() 
	{
		int j = front;
		for (int i= 0 ;i<size;i++) 
		{
			System.out.printf("The %d num is %d \n", i, array[j]);
			j = (j + 1) % array.length;
		}
	}
	public static void main(String[] args) throws Exception 
	{
		MyArrayQueue queue = new MyArrayQueue(7);
		queue.enqueue(7);
		queue.enqueue(6);
		queue.enqueue(5);
		queue.enqueue(4);
		queue.print();
		queue.dequeue();
		queue.print();
		queue.dequeue();
		queue.print();
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值