java实现数组模拟环形队列

使用Java实现数组模拟环形队列
给出了队列是否满 队列中有效元素等函数和判断条件

package baoxinhai_test_datastructure;

import java.util.Scanner;

/*
 * 使用数组模拟环形队列  环形队列预留一个元素 即元素的最大数为maxsize-1
 * @author bxh
 */
public class CircleArrayQueue {
	public static void main(String[] args) {
		CircleQueue queue = new CircleQueue(4);   //最大的有效元素为3个
		boolean flag=true;
		Scanner input=new Scanner(System.in);
		char key=' ';
		while(flag)
		{
			System.out.println("输入s(show)显示队列:");
			System.out.println("输入a(add)添加元素:");
			System.out.println("输入g(get)取出队列中的元素:");
			System.out.println("输入h(head)打印队列尾部元素:");
			System.out.println("输入e(exit)退出循环:");
			key=input.next().charAt(0);
			switch (key) {
			case 's': 
				 queue.show();
				break;
			case 'a': 
				try {
					 System.out.println("请输入需要添加到队列中的元素:");
						int value=input.nextInt();
						 queue.addqueue(value);
				} catch (Exception e) {
					// TODO: handle exception
					System.out.println(e.getMessage());
				}
				
				break;
			case 'g': 
				 try {
					 int x=queue.getqueue();
					 System.out.println("取出的元素是"+x);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case 'h': 
				 try {
				int y=queue.showback();
				System.out.println("队列头部的元素为"+y);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case 'e': 
				 flag=false;
				break;
			default:
				break;
			}
		}
		input.close();
		System.out.println("程序退出!");
	}
}
class CircleQueue
{
	private int maxsize;
	private int rear;
	private int front;
	public  int[] queue;
	
	public CircleQueue(int maxsize1) {
		maxsize=maxsize1;
		queue=new int[maxsize];
	}
	

	 //判断是否为空
	 public boolean isempty() {
		 return rear==front;
	 }
	 //判断队列是否已经满了
	 public boolean isfull()
	 {
		 return (rear+1)%maxsize==front;
	 }
	 //往队列中添加数据
	 public void addqueue(int x) {
		if(isfull())       //先判断队列是否满
		{
			throw new RuntimeException("队列已经满了,无法再继续添加队列!");
		}
		queue[rear]=x;
		rear=(rear+1)%maxsize;
	}
	 //取出队列中的元素
	public int getqueue() {
		if(isempty())
		{
			throw new RuntimeException("队列为空,目前没有元素可以取出!");
		}
		int value=queue[front];
		front++;
		return value;
	}
	
	//展示队列中的元素
	public void show() {
		if(isempty())
		{
			System.out.println("当前队列中没有元素");
		}
		for(int i=front;i<front+size();i++)
		{
			System.out.printf("queue[%d]=%d",i%maxsize,queue[i%maxsize]);
			System.out.println();
		}
	}
	//返回当前队列中的有效元素个数
	public int size() {
		return (rear+maxsize-front)%maxsize;
	}
	//展示队头的元素
	public int showback() {
		if(isempty())
		{
			throw new RuntimeException("队列为空,目前没有元素可以展示!");
		}
		return queue[front];
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值