欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java实现队列

程序员文章站 2024-03-01 13:21:46
...

一、什么是队列

队列是一种数据结合,它的特点是先进先出(FIFO)

二、实现队列

public class MyQueue {
	private Object[] queue = null;
	private int capacity = 0;
	private int count = 0;

	public MyQueue(int capacity) {
		this.capacity = capacity;
		queue = new Object[capacity];
	}

	public void put(Object obj) {
		if (isFull()) {
			return;
		}
		queue[count++] = obj;
	}

	public Object remove() {
		if (isEmpty()) {
			return null;
		}
		Object obj = queue[0];
		count--;
		for (int i = 0; i < count; i++) {
			queue[i] = queue[i + 1];
		}
		return obj;
	}

	public boolean isFull() {
		if (count == capacity) {
			System.out.println("队列已经满了");
			return true;
		}
		return false;
	}

	public boolean isEmpty() {
		if (count == 0) {
			System.out.println("队列是空的");
			return true;
		}
		return false;
	}
}

它有四种方法:put(),remove(),isFull(),isEmpty()。分别是添加,移除,是否为满,是否为空。
测试它

	public static void main(String[] args) {
		MyQueue mq = new MyQueue(5);
		System.out.println(mq.remove());
		mq.put(1);
		mq.put(2);
		mq.put(3);
		mq.put(4);
		mq.put(5);
		mq.put(6);
		System.out.println(mq.remove());
		System.out.println(mq.remove());
		System.out.println(mq.remove());
		System.out.println(mq.remove());
		System.out.println(mq.remove());
	}

结果为
队列是空的
null
队列已经满了
1
2
3
4
5