一个简单的队列

public class MyQueue {
	private long[] arr;

	private int front;

	private int end;
	// 有效数据的大小
	private int elements;

	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(int value) {
		if (end == arr.length - 1) {
			end = -1;
		}
		arr[++end] = value;
		elements++;
	}

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

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

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

	// 判断是否为满
	public boolean isFull() {
		return elements == arr.length;
	}

	public static void main(String[] args) {
		MyQueue myQueue = new MyQueue();
		myQueue.insert(23);
		myQueue.insert(45);
		myQueue.insert(13);
		myQueue.insert(1);
		System.out.println(myQueue.isFull());
		System.out.println(myQueue.isEmpty());
		System.out.println(myQueue.peek());
		while (!myQueue.isEmpty()) {
			myQueue.remove();
		}

		myQueue.insert(23);
	}
}

猜你喜欢

转载自luyulong.iteye.com/blog/2222571