用数组结构实现固定大小的队列

public class QueByArrary {
	private Integer[] arr;
	private Integer size;
	private Integer first;
	private Integer last;
	
	public QueByArrary(int initSize){
		if(initSize<=0){
			throw new IllegalArgumentException("The init size is less than 0");
		}
		arr=new Integer[initSize];
		size=0;
		first=0;
		last=0;
	}
	
	public void push(Integer num){
		if(size==arr.length){
			throw new ArrayIndexOutOfBoundsException("The que is full");
		}
		size++;
		last=(last==arr.length?0:last);
		arr[last++]=num;
	}
	/**
	 * 弹出队列第一个位置的数,不移除
	 * @return
	 */
	public Integer peek(){
		if(size==0){
			throw new ArrayIndexOutOfBoundsException("The queue is empty");
		}
		return arr[first];
	}
	
	/**
	 * 弹出队列第一个位置的数并移除
	 * @return
	 */
	public Integer pop(){
		if(size==0){
			throw new ArrayIndexOutOfBoundsException("The queue is empty");
		}
		size--;
		int temp=first;
		first=(first==arr.length-1?0:first+1);
		return arr[temp];
	}

猜你喜欢

转载自blog.csdn.net/qq_42667028/article/details/86665316