数据结构之java实现队列

使用数组实现循环队列
队列空:front == rear
队列满:(rear + 1) % maxSize == front; 容量为队列最大容量maxSize - 1
进队列:rear循环进1,再进入队列
出队列:front循环进1,再出队列

rear与front要保持一致,要么先+1在操作,要么先操作再+1,下面队列采用第一种形式

该循环列表最大容量为maxSize-1,因为使队满条件成立时,会空出一个单元

public class Queue<E> {
	
	E[] queue;//采用数组形式进行存储
	int front;//队头指针负责出队
	int rear;//队尾指针负责入队
	int maxSize;//队列中最大容量
	private final static int DEFAULT_SIZE = 10;//默认容量
	
	public Queue() throws Exception{
		
		this(DEFAULT_SIZE);
	}
	
	public Queue(int capacity) throws Exception{
		
		if(capacity < 0)
			throw new Exception("Illegal capacity ");
		
		queue = (E[]) new Object[capacity];
		front = 0;
		rear = 0;
		maxSize = capacity;
		
		
	}
	//进入队列运算算法
	public boolean enQueue(E obj) throws Exception{
		
		if(obj == null)
			return false;
		//如果队列已满 抛出异常
		if((rear + 1) % maxSize == front)
			throw new Exception("Queue is full " );
		//进入队列操作
		/*这个位置关于rear的操作后面会有介绍*/
		rear = (rear + 1) % maxSize;//队尾指针+1
		queue[rear] = obj;
		return true;
	
	}
	//出队列运算算法
	public E deQueue() throws Exception{
		
		if(rear == front)
			throw new Exception("Queue is full ");
		front = (front + 1) % maxSize;
		return queue[front];
		
	}
	//求队列中元素个数
	public int count(){
		 
		return (rear + maxSize - front) % maxSize;
	}
	//判断队列是否为空
	public boolean isEmpty(){
		
		return (front == rear) ? true : false;
	}
	//输出队列,从对队头到队尾
	public void display() throws Exception{
		
		if(isEmpty())
			throw new Exception("Queue is empty ");
		int index = front;
		while(index != rear){
			
			System.out.println(this.deQueue());
			index  = (index + 1) % maxSize;
		}
			
		
	}
	
	public static void main(String[] args) throws Exception{
		
		Queue queue = new Queue(101);
		
		for(int i=1;i<=100;i++)
			queue.enQueue(i);
		System.out.println("队列元素个数:" + queue.count());
		System.out.println("队列是否为空:" + queue.isEmpty());
		System.out.println("**********************************");
		
		for(int i=1;i<=50;i++)
			queue.deQueue();
		System.out.println("队列元素个数:" + queue.count());
		System.out.println("队列是否为空:" + queue.isEmpty());
		System.out.println("**********************************");
		
		for(int i=1;i<=50;i++)
			queue.deQueue();
		System.out.println("队列元素个数:" + queue.count());
		System.out.println("队列是否为空:" + queue.isEmpty());
		
		
	}
	

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值