数组实现队列,先进先出

代码

public class ArrayQueueDemo {

	public static void main(String[] args) {
		
		ArrayQueue queue = new ArrayQueue(3);
		char key = ' ';
		Scanner scanner = new Scanner(System.in);
		boolean loop = true;
		while(loop){
			System.out.println("s:显示队列");
			System.out.println("e:退出程序");
			System.out.println("a:添加数据到队列");
			System.out.println("g:从队列取出数据");
			System.out.println("h:查看队列头的数据");
			key = scanner.next().charAt(0);
			switch (key) {
			case 's':
				queue.showQueue();
				break;
			case 'a':
				System.out.println("请输入一个数:");
				int num = scanner.nextInt();
				queue.addQueue(num);
				break;
			case 'g':
				try {
					int result = queue.getQueue();
					System.out.printf("取出的数据是%d\n",result);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case 'h':
				try {
					int result = queue.headQueue();
					System.out.printf("队列头的数据是%d\n",result);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case 'e':
				scanner.close();
				loop = false;
				break;
			default:
				break;
			}
		}
		System.out.println("程序退出");
	}
}
class ArrayQueue{
	//队列的最大容量
	private int maxSize;
	//队列头
	private int front;
	//队列尾
	private int rear;
	//该数组用于存放数据,模拟队列
	private int[] arr;
	//初始化队列数据
	public ArrayQueue(int maxSize){
		this.maxSize = maxSize;
		this.arr = new int[maxSize];
		//指向队列头部,分析出front是指向队列头的前一个位置
		this.front = -1;
		//指向队列尾,指向队列尾的数据(即就是队列最后一个数据)
		this.rear = -1;
	}
	//判断队列是否满
	public boolean isFull(){
		return this.rear == this.maxSize - 1;
	}
	//判断队列是否为空
	public boolean isEmpty(){
		return this.rear == this.front;
	}
	//添加数据到队列
	public void addQueue(int num){
		if(isFull()){
			System.out.println("队列已满,请稍后再添加。");
			return;
		}
		this.rear ++;//rear后移
		this.arr[this.rear] = num;
	}
	//获取队列数据,出队列
	public int getQueue(){
		if(isEmpty()){
			throw new RuntimeException("队列为空,不能取数据。");
//			System.out.println("队列为空。");
//			return -1;
		}
		this.front ++;//front后移
		return this.arr[this.front];
	}
	//显示队列的所有数据
	public void showQueue(){
		if(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(isEmpty()){
			throw new RuntimeException("队列为空。");
		}
		return this.arr[++ this.front];
	}
}

存在的问题

/**

  • TODO 存在的问题是:添加完数据,然后再全部取出数据,
  • 此时,虽然队列已经为空,但是数组仍然占有着位置,所以再次添加依然是满的状态
  • 为了解决该问题,可以用环形队列解决
    */
posted @ 2021-08-23 16:08  卡卡罗特琪琪  阅读(304)  评论(0编辑  收藏  举报