首页 > 代码库 > java数据结构队列

java数据结构队列

队列类似于现实生活中的排队。队列是先进先出的原则,只允许在队列头部去除元素,队列尾部添加元素。

下面是分别用数组和链表为存储结构实现的队列

public interface Queue<T> {
	
	int size();
	
	T remove();
	
	void add(T element);
	
	boolean isEmpty();
	
	void clear();
	
	boolean hasElement();
}

public class ArrayQueue<T> implements Queue<T>{

	//数组的默认大小
	private static final int DEFAULT_SIZE = 10;
	
	//默认用数组存储
	private Object[] values = new Object[DEFAULT_SIZE];
	
	private int arrayLength = DEFAULT_SIZE;
	
	//
	private int top = -1;
	
	private int bottom = -1;
	
	@Override
	public int size() {
		return (top - bottom) + 1;
	}

	//队列顶端删除元素
	@SuppressWarnings("unchecked")
	@Override
	public T remove() {
		if(isEmpty()){
			throw new NullPointerException();
		}
		T value = http://www.mamicode.com/(T)values[++top];>
public class LinkedList<T> implements Queue<T> {

	private int size = 0;
	
	private Item top ;
	
	private Item bottom;
	
	private class Item{
		private T data;
		
		private Item next;
		
		Item(T data,Item next){
			this.data = http://www.mamicode.com/data;>