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

循环队列的Java简单实现

程序员文章站 2022-07-14 13:48:30
...

基本概念

队列:一种先进先出(First In First Out,FIFO)的数据结构。其来自于我们日常生活中的排队问题,排在前面的先获得服务。
循环队列:长度固定的队列。其优势是循环利用内存资源,入队和出队都是O(1)的时间复杂度。通常,我们使用一个数组来实现循环队列,对头通过front指针标记,对尾通过tail指针标记。当front = tail时,队列为空;当tail + 1 = head时,队列为满。
基于这些约定,就可以编程实现循环队列了。

Java实现

抽象出队列接口。

/**
 * A First In Fist Out (FIFO) data structure.
 * 
 * @author Xingjian
 * @since 2019/09/20
 * @param <T> element type
 */
public interface Queue<T> {
	/**
	 * add element to Queue.
	 * 
	 * @param element
	 * @return true, element added successfully. Otherwise,false.
	 */
	boolean enQueue(T element);

	/**
	 * get element from Queue.
	 * 
	 * @return element, removed from Queue.Or null if Queue is empty.
	 */
	T deQueue();

	/**
	 * test whether this Queue is empty.
	 * 
	 * @return true, if Queue is empty. Otherwise,false.
	 */
	boolean isEmpty();
}

循环队列实现。

/**
 * Circular Queue implementation.
 * 
 * @author Xingjian
 * @since 2019/09/20
 * @param <T> element type
 */
public class CircularQueue<T> implements Queue<T> {
	/**
	 * element stored in this array.
	 */
	private T elements[];

	/***
	 * front pointer.
	 */
	private int front;

	/**
	 * tail pointer.
	 */
	private int tail;

	/**
	 * construct a Circular Queue with given length.
	 * 
	 * @param length
	 */
	@SuppressWarnings("unchecked")
	public CircularQueue(int length) {
		if (length <= 0) {
			throw new IllegalArgumentException("length must be a positive integer.");
		}
		this.elements = (T[]) new Object[length];
		this.front = 0;
		this.tail = 0;
	}

	@Override
	public boolean enQueue(T element) {
		if ((tail + 1) % elements.length == front) {
			// there is no space to add element.
			return false;
		}
		elements[tail] = element;
		tail = (tail + 1) % elements.length;
		return true;
	}

	@Override
	public T deQueue() {
		if (isEmpty()) {
			return null;
		}
		T e = elements[front];
		front = (front + 1) % elements.length;
		return e;
	}

	@Override
	public boolean isEmpty() {
		return front == tail;
	}
}
相关标签: 循环队列