Java实现数据结构的循环队列

package com.lee.queue;

public class Queue {
	private int maxSize;//队列长度
	private int front;	//指向队列第一个元素的位置,默认值为0
	private int rear;	//指向队列最后一个元素的后一个位置,默认值是0
	private int[] data; //存储队列的数组
	
	//初始化队列
	public Queue(int maxSize) {
		this.maxSize = maxSize;
		data = new int[maxSize];
		front = 0;
		rear = 0;
	}
	
	//判断队列是否为空
	public boolean isNull() {
		return front == rear;
	}
	
	//判断队列是否为满
	public boolean isFull() {
		return (rear + 1) % maxSize == front;
	}
	
	//入队
	public void addQueue(int element) {
		//判断队列是否为满
		if(isFull()) {
			System.out.println("队列满,不能加入");
			return;
		}
		data[rear] = element;
		//将rear后移,考虑取模
		rear = (rear + 1) % maxSize;
	}
	
	//出队
	public int getQueue() {
		//判断是否为空
		if(isNull()) {
			throw new RuntimeException("队列为空,不能取数据");
		}
		int value = data[front];
		//front后移,考虑取模
		front = (front + 1) % maxSize;
		return value;
	}
	
	//显示队列所有数据
	public void show() {
		if(isNull()) {
			System.out.println("队列空,没有数据");
			return;
		}
		for(int i = front; i < front + size(); i++) {
			System.out.println("data[" + i % maxSize + "]:" + data[i % maxSize]);
		}
	}
	
	//返回有多少个有效元素
	public int size() {
		return (rear + maxSize - front) % maxSize;
	}
	
	//显示队列头数据
	public int peek() {
		if(isNull()) {
			throw new RuntimeException("队列为空");
		}
		return data[front];
	}
	
	
}
发布了63 篇原创文章 · 获赞 28 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41286145/article/details/102510111