Java数据结构与算法学习(4)-数组模拟队列

数组模拟队列

一、思路

队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下图:
在这里插入图片描述
1)MaxSize为该队列的最大容量

2)因为队列的输入和输出是分别从前后端来处理,因此需要两个变量front及rear分别记录队列前后端的下标,front会随着数据输出而改变,而rear是随着数据的输入而改变。
2.1front表示最前的数据的前一个下标,rear表示最后的数据的下标。

3)当我们将数据存入队列时称为“addQueue”,addQueue的处理需要有两个步骤:思路分析
3.1 首先需要判断队列的容量是否已满
3.2 如果已满(rear==maxSize-1)则存入失败,队列已满,如果未满,则将rear+1并且将rear+1对应的下标赋值。

4)当我们将数据从队列中取出时称为“getQueue”,getQueue的处理需要有两个步骤:
4.1 首先需要判断队列是否为空
4.2 如果队列为空(rear == front)则取数据失败,如果队列不为空,则将front+1并返回front+1对应下标的数据。

二、代码实现

public class ArrayQueue {

	private int maxSize;//队列大小
	private int front;//队列头
	private int rear;//队列尾
	private int[] arr;//用数组模拟队列
	
	//参数为队列大小,同时初始化队列头,队列尾参数
	public ArrayQueue(int maxSize) {
		this.maxSize = maxSize;
		arr = new int[maxSize];
		front = -1;
		rear = -1;
	}
	
	public boolean isFull() {
		return rear == maxSize - 1; //通过rear是否为队列大小-1,来判断队列是否满了
	}
	
	public boolean isEmpty() {
		return front == rear;//通过front是否等于rear来判断,队列是否为空
	}
	
	public int getQueue() {
		if(isEmpty()) {
			throw new RuntimeException("队列为空,无法获取信息");
		}
		return arr[++front];
	}
	
	public void addQueue(int queue) {
		if(isFull()) {
			System.out.println("队列已满,无法增加队列!");
			return;
		}
		arr[++rear] = queue;
	}
	
	public void showQueue() {
		if(isEmpty()) {
			System.out.println("队列为空");
			return;
		}
		for(int i = 0;i < arr.length;i++) {
			System.out.println("arr["+i+"]="+arr[i]);
		}
	}
	
	public int headQueue() {
		if(isEmpty()) {
			throw new RuntimeException("队列为空");
		}
		return arr[front+1];
	}
}

测试代码

import java.util.Scanner;

public class Test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayQueue aq = new ArrayQueue(3);
		char key = ' ';//模拟用户输入
		boolean loop = true;
		Scanner sc = new Scanner(System.in);
		while(loop) {
			System.out.println("s(show):显示队列");
			System.out.println("e(exit):退出程序");
			System.out.println("a(add):添加数据到队列");
			System.out.println("g(get):从队列中取出数据");
			System.out.println("h(head):查看队列头数据");
			key = sc.next().charAt(0);
			switch (key) {
			case 's':
				aq.showQueue();
				break;
			case 'e':
				loop = false;
				sc.close();
				break;
			case 'a':
				System.out.println("请输入一个数:");
				int i = sc.nextInt();
				aq.addQueue(i);
				break;
			case 'g':
				try {
					int queue = aq.getQueue();
					System.out.println("您取出的数为:"+queue);
				} catch (Exception e) {
					System.out.println("队列为空,无法获取数据!");
				}
				break;
			case 'h':
				try {
					int queue = aq.headQueue();;
					System.out.println("队列头数据为:"+queue);
				} catch (Exception e) {
					System.out.println("队列为空,无法获取队列头!");
				}
				break;
			default:
				break;
			}
		}
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值