数据结构与算法02 队列1

  1. 队列是一个有序列表,可以用数组或者是链表来实现。
  2. 遵守先入先出原则。
  3. 示意图如下:
    在这里插入图片描述
使用数组模拟队列
  1. maxSize是队列的最大容量。front与rear分别标记队列的前后两端。front(头指针)随着数据输出改变,rear(尾指针)随着数据输入改变。
  2. 判断队列为空的条件:front == rear
  3. 判断队列满的条件: rear = maxSize - 1
class ArrayQueueDemo{
	private int maxSize ;
	private int front; //头指针
	private int rear; //尾指针
	private int[] arr; //存放数组,模拟队列
	
	public ArrayQueueDemo(int maxSize) {
		this.maxSize = maxSize;
		arr = new int[maxSize];
		front = -1;
		rear = -1;
	}
	
	public boolean isFull() {
		if(rear == maxSize -1) {
			return true;
		}
		return false;
//		return rear == maxSize -1;  //一步到位
	}
	
	public boolean isEmpty() {
		return rear == front;
	}
	
	//添加數據到隊列
	public void addQueue(int n) {
		if(isFull()) {
			System.out.println("队列已满");
		}else {
			arr[++rear] = n;			
		}
	}
	
	//出隊列
	public int getQueue(){
		if(isEmpty()) {
//			System.out.println("队列为空,不能取数据");
			throw new RuntimeException("队列为空,不能取数据");
		}else {
			int date = arr[++front];
			return date;
		}
	}
	
	//显示队列所有数据
	public void showQueue() {
		if(isEmpty()) {
			System.out.println("队列为空");
		}else {
			for(int i = 0; i < arr.length; i++) {
				System.out.println(arr[i]);
			}
		}
	}
	
	//获得队列头数据
	public void headQueue() {
		if(isEmpty()) {
			System.out.println("队列为空,没有数据");
		}
		System.out.println(arr[front + 1]);
	}
}

测试代码如下:

import java.util.Scanner;

public class ArrayQueue {
	public static void main(String[] args) {
		
		ArrayQueueDemo queue = new ArrayQueueDemo(3);
		char key;//接受用户输入
		Scanner scanner = new Scanner(System.in);
		boolean flag = true;
		while(flag) {
			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 = scanner.next().charAt(0);
			
			switch(key) {
			case 's':
				queue.showQueue();
				break;
				
			case 'a':
				System.out.println("输入一个数");
				int value = scanner.nextInt();
				queue.addQueue(value);
				break;
			
			case 'g':
				try {
					int res = queue.getQueue();
					System.out.println("取出的数据为:" + res);
				}catch(Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			
			case 'h':
				queue.headQueue();			
				break;
			
			case 'e':
				scanner.close();
				flag = false;
				break;
			}
			
		}
	}
}

存在的问题:

  1. 队列使用一次就不能使用,没有达到复用效果。后续使用环形队列:取模。
  2. showQueue()方法存在问题,需要进一步修改。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值