Java数据结构-队列

队列中添加数据、取出数据,访问队头元素、判断队列是否为空、判断队列是否满了

public class MyQueue {

	private long[] arr;
	// 有效数据大小
	private int elements;
	// 对头
	private int front;
	// 队尾
	private int end;

	// 无参构造
	public MyQueue() {
		arr = new long[10];
		elements = 0;
		front = 0;
		end = -1;
	}

	// 有参构造,参数为数组大小
	public MyQueue(int maxsize) {
		arr = new long[maxsize];
		elements = 0;
		front = 0;
		end = -1;
	}

	/*
	 * 添加数据,从队尾插入
	 */
	public void insert(long value) {
		if (end == arr.length - 1) {
			end = -1;
		}
		arr[++end] = value;
		elements++;
	}

	/*
	 * 删除数据,从对头删除
	 */
	public long remove() {
		long value = arr[front++];
		if (front == arr.length) {
			front = 0;
		}
		elements--;
		return value;
	}

	/*
	 * 查看对头数据
	 */
	public long peek() {
		return arr[front];
	}

	/*
	 * 返回队列中有效元素个数
	 */
	public int size() {
		return elements;
	}

	/*
	 * 判断队列是否为空
	 */
	public boolean isEmpty() {
		return elements == 0;
	}

	/*
	 * 判断队列是否满了
	 */
	public boolean ifFull() {
		return elements == arr.length;
	}

}

写一个测试类

public class TestMyQueue {
	public static void main(String[] args) {
		MyQueue myQueue = new MyQueue(5);
		//添加数据
		myQueue.insert(99);
		myQueue.insert(77);
		myQueue.insert(33);
		myQueue.insert(22);
		myQueue.insert(11);
		//查看对头数据
		System.out.println("对头数据:"+myQueue.peek());
		//有效元素个数
		System.out.println("有效元素个数:"+myQueue.size());
		//判断是否满了
		System.out.println("是否满了:"+myQueue.ifFull());
		//取出数据,先判断是否为空再打印
		while (!myQueue.isEmpty()) {
			System.out.print(myQueue.remove()+" ");
		}
	}

}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值