Java数据结构与算法学习笔记--数组模拟队列

package com.queue;

/*队列基本介绍:
 * 	1、队列是一个有序列表,可以用数组或链表来实现
 * 	2、遵循先入先出的原则,即:县存入队列的数据,要先取出,后存入的要 后取出
 * 	
 * 数组模拟队列基本思路:
 * 	1、对垒本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下图,其中maxSize
 * 	   是该队列最大容量
 * 	2、因为队列的输出,输入时分别从前后端来处理,因此需要使用两个变量front和rear分表记录队列前后端
 *   的下标,front会随着数据输出而变动,而rear则是随着数据输入而变动
 * 	3、当我们将数据存入队列时称为 addQueue,addQueue的处理需要有两个步骤,思路分析:
 * 		1)将尾指针往后移:rear+1,当front == rear时,队列尾空
 * 		2)若尾指针rear小于队列的最大下标maxSize-1,则将数据存入rear所指的数组元素中,否则无法存入数据,
 * 			rear==maxSize-1,时队列满
 * 问题分析及优化
 * 	1、目前数组使用一次就不能用,没有达到复用的效果
 * 	2、将这个数组使用算法,该进成一个环形的队列
 */

//使用数组模拟对队列编写一个ArrayQueue类
class ArrayQueue
{
	private int maxSize; // 表示数组的最大容量
	private int front;// 队列头
	private int rear;// 队列尾
	private int[] arr;// 该数组用于存放数据,模拟队列
	
	public ArrayQueue(int arrMaxSize)
	{
		this.maxSize=arrMaxSize;
		arr=new int[this.maxSize];
		front=-1;//指向队列头部,分析出front是指向对垒头的前一个位置
		rear=-1;//执行队列尾,指向队列尾的数据(即就是队列最后一个元素)
	}
	
	//判断队列是否满
	public boolean isFull()
	{
		return this.rear == this.maxSize-1;
	}
	
	//判断队列是否为空
	public boolean isEmpty()
	{
		return this.rear == this.front;
	}
	
	//添加数据到队列
	public void addQueue(int n)
	{
		//判断队列是否为空
		if(this.isFull())
		{
			System.out.println("队列满,不能加入数据~");
			return;
		}
		this.rear++;
		this.arr[this.rear]=n;
	}
	
	//获取队列的数据,出队列
	public int getQueue()
	{
		//判断队列是否为空
		if(this.isEmpty())
		{
			// 通过抛出异常处理
			throw new RuntimeException("队列空,不能取数据");
		}
		this.front++;
		return this.arr[this.front];
	}
	
	//显示队列的所有数据
	public void showQueue()
	{
		if(this.isEmpty())
		{
			System.out.println("队列为空,没有数据");
			return;
		}
		for(int i=0;i<arr.length;i++)
		{
			System.out.printf("arr[%d]=%d\n",i,arr[i]);
		}
	} 
	 
	//显示队列的头数据,不是取数据
	public int headQueue()
	{
		//判断队列是否为空
		if(this.isEmpty())
		{
			throw new RuntimeException("队列为空,没有数据");
		}
		return this.arr[this.front+1];
	}
}
public class ArrayQueueDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayQueue arrq = new ArrayQueue(3);
		arrq.showQueue();
		arrq.addQueue(10);
		arrq.addQueue(20);
		arrq.addQueue(30);
		arrq.addQueue(40);
		arrq.showQueue();
		int value=arrq.getQueue();
		System.out.printf("get value is %d\n",value);
		int head=arrq.headQueue();
		System.out.printf("head of queue is %d\n",head);
		
	}

}

运行结果为:

队列为空,没有数据
队列满,不能加入数据~
arr[0]=10
arr[1]=20
arr[2]=30
get value is 10
head of queue is 20
发布了12 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/redrose2100/article/details/104603349