java_basic_ArrayStack_02 固定数组实现队列

【原理】:

  1. 定义构造函数,初始化

  2. 注意push更新逻辑:每次size++, 把当前数给end指向, end更新如果end指向最后一个了arr.length,返回初始位置

  3. 注意poll更新逻辑:size为0,报错, size--, start位置用tmp记录一下,返回这时候的start位置,start需要更新。

【代码】


// 用固定数组实现队列

public class ArrayStack_02 {
	private Integer[] arr;
	private Integer size = 0;
	private Integer start = 0;
	private Integer end = 0;
	// 定义构造函数,初始化
	public ArrayStack_02(int initSize) {
		if (initSize < 0) {
			throw new IllegalArgumentException("The init size is less than 0");
		}
		arr = new Integer[initSize];
		size = 0;
		start = 0;
		end = 0;
	}
	
	// 注意push更新逻辑:每次size++, 把当前数给end指向, end更新如果end指向最后一个了arr.length,返回初始位置
	public void push(int obj) {
		if ( size == arr.length) {
			throw new IllegalArgumentException("The queue is full");
		}
		size++;
		arr[end] = obj;
		end = end == arr.length ? 0 : end+1;
	}
	
	// 注意poll更新逻辑:size为0,报错, size--, start位置用tmp记录一下,返回这时候的start位置,start需要更新。
	public Integer poll() {
		if (size == 0) {
			throw new IllegalArgumentException("The queue is empty");
		}
		size--;
		int tmp = start;
		start = start == arr.length-1 ? 0 : start + 1;
		return arr[tmp];
		
	}
	
	public Integer peek() {
		if (size == 0) {
			return null;
		}
		return arr[start];
	}
	
	
	public static void main(String[] args) {
		int initSize = 3;
		ArrayStack_02 myQueue = new ArrayStack_02(initSize);
		myQueue.push(10);
		myQueue.push(11);
		myQueue.push(12);

		for(int i = 0 ; i < initSize; i++) {
			System.out.println("第" + i + "次弹出的数为:" + myQueue.poll());
			
		}
		
		
	}
	
}

【结果】

第0次弹出的数为:10
第1次弹出的数为:11
第2次弹出的数为:12

【笔记】

猜你喜欢

转载自blog.csdn.net/sinat_15355869/article/details/81807336