数据结构----环形队列

继续跟着教程写的环形队列,环形队列会空了一个空间,所以注意队列的实际最大容量会和自己所想的最大容量不一样,在代码要考虑这个问题怎么解决。另外注意取模,可以解决上一篇中代码存在的问题。

import java.util.Scanner;

public class CircleArrayQueueDemo {
	public static void main(String[] args) {
		CircleArray queue=new CircleArray(4);
		char key=' ';
		Scanner sc=new Scanner(System.in);
		boolean loop=true;
		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':
				queue.showQueue();
				break;
			case 'a':
				System.out.println("输入一个数");
				int value=sc.nextInt();
				queue.addQueue(value);
				break;
			case 'g':
				try {
					int res=queue.getQueue();
					System.out.printf("取出的数据是%d\n",res);
				}catch(Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case 'h':
				try {
					int res=queue.headQueue();
					System.out.printf("队列头的数据是%d\n",res);
				}catch(Exception e){
					System.out.println(e.getMessage());
				}
				break;
			case 'e':
				sc.close();
				loop=false;
				break;
				default:
					break;
			}
			
		}
	}
}

class CircleArray{
	private int maxSize;
	private int front;
	private int rear;
	private int[] arr;
	
	public CircleArray(int arrMaxSize) {
		maxSize=arrMaxSize+1;//留了一个空位置
		arr=new int[maxSize];
	}
	
	//判断队列是否满
	public boolean isFull() {
		return (rear+1)%maxSize==front;
	}
	
	//判断队列是否为空
	public boolean isEmpty() {
		return rear==front;
	}
	
	//添加数据到队列
	public void addQueue(int n) {
		if(isFull()) {
			System.out.println("队列满,不能加入数据");
			return;
		}
		arr[rear]=n;
		rear=(rear+1)%maxSize;
	}
	
	//获取队列的数据,出队列
	public int getQueue() {
		if(isEmpty()) {
			throw new RuntimeException("队列空,不能取出数据");
		}
		int value=arr[front];
		front=(front+1)%maxSize;
		return value;
	}
	
	//显示队列的所有数据
	public void showQueue() {
		if(isEmpty()) {
			System.out.println("队列空的,没有数据");
			return;
		}
		for(int i=front;i<front+size();i++) {
			System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);
		}
	}
	
	//显示队列有效数据的个数,用于show使用
	public int size() {
		return (rear+maxSize-front)%maxSize;
	}
	
	//显示队列的头数据,注意不是取出数据
	public int headQueue() {
		if(isEmpty()) {
			throw new RuntimeException("队列空的,没有数据");
		}
		return arr[front];
	}
}
imn
发布了33 篇原创文章 · 获赞 0 · 访问量 370

猜你喜欢

转载自blog.csdn.net/qq_45955462/article/details/104599321
今日推荐