数组模拟队列(代码实现)

数据结构可分为两种,第一种是线性结构,第二种是非线性结构,线性结构又分为连续存储和链表存储。
常见的线性结构有数组,链表,队列,栈;
以下是数组模拟队列的实现(队列特点就是先进先出):


//数组模拟队列  
public class ArrayQueueDemo {
	
	public static void main(String[] args) {
		ArrayQueue queue = new ArrayQueue(3);
		char key = ' '; //接收用户输入
		Scanner scanner = new Scanner(System.in);
		boolean f = true;
		while(f){
			System.out.println("s:显示队列");
			System.out.println("a:添加数据");
			System.out.println("e:退出程序");
			System.out.println("h:显示头部数据");
			System.out.println("g:取出数据");
			key = scanner.next().charAt(0);
			switch(key) {
			case 's':
				queue.show();
				break;
			case 'a':
				System.out.println("轻输入一个数据");
				int value = scanner.nextInt();
				queue.add(value);
				break;
			case 'h':
				try {
					int res = queue.head();
					System.out.println(res);
				} catch (Exception e) {
					// TODO: handle exception
					System.out.println(e.getMessage());
				}
				break;
			case 'g':
				try {
					int res = queue.get();;
					System.out.println(res);
				} catch (Exception e) {
					// TODO: handle exception
					System.out.println(e.getMessage());
				}
				break;
			case 'e':
				scanner.close();
				f = false;
				break;
			default:
				break;
			}
		}
		System.out.println("退出程序");
	}
	
}

	class ArrayQueue{
		private int maxSize; // 队列的最大容量
		private int front; //指向队列的头部
		private int rear; //指向队列的尾部
		private int[] arr;//使用数组创建队列
		
		//创建队列的构造器
		public ArrayQueue(int arrMaxSize) {
			maxSize = arrMaxSize;
			arr = new int[maxSize];
			front = -1; //队列头部  指向的是头部前面的位置
			rear = -1;// 队列尾部 包含尾部数据
		}
		
		//判断队列是否满了
		public boolean isFull() {
			return rear == maxSize - 1;
		}
		//判断队列是否为空
		public boolean isNull() {
			return front == rear;
		}
		
		//将数据添加到队列中
		public void add(int num ) {
			if(isFull()) {
				System.out.println("队列已经满了,不能添加数据");
				return;
			}
			rear ++;
			arr[rear] = num;
			
		}
		
		//取出队列数据  相当于删除数据
		public int get() {
			if(isNull()) {
				throw new RuntimeException("队列为空,没有数据");
			}
			front++;
			return arr[front];
		}
		
		//显示队列的全部数据
		public void show() {
			if(isNull()) {
				System.out.println("队列为空,没有数据");
				return;
			}
			for(int i = 0; i<arr.length;i++) {
				System.out.println(arr[i]);
			}
		}
		
		//显示队列头部数据
		public int head() {
			if(isNull()) {
				throw new RuntimeException("队列为空");
			}
			return arr[front+1];
		}
		
		
		
		
		
		
		
		
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想养一只!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值