1. 程式人生 > >演算法練習bat----------10用陣列結構實現大小固定的佇列和棧

演算法練習bat----------10用陣列結構實現大小固定的佇列和棧

1.使用陣列實現大小固定的棧(使用變數index來模擬棧中的指標)


	public static class ArrayStack {
		private Integer[] arr;
		private Integer size;

		public ArrayStack(int initSize) {
			if (initSize < 0) {
				throw new IllegalArgumentException("The init size is less than 0");
			}
			arr = new Integer[initSize];
			size = 0;
		}

		public Integer peek() {
			if (size == 0) {
				return null;
			}
			return arr[size - 1];
		}

		public void push(int obj) {
			if (size == arr.length) {
				throw new ArrayIndexOutOfBoundsException("The queue is full");
			}
			arr[size++] = obj;
		}

		public Integer pop() {
			if (size == 0) {
				throw new ArrayIndexOutOfBoundsException("The queue is empty");
			}
			return arr[--size];
		}
	}

	
	public static void main(String[] args) {

	}

2.使用陣列來實現固定大小的佇列

public static class ArrayQueue {
		private Integer[] arr;
		private Integer size;//當前陣列中存放的數字,要求size<arr.length
		private Integer first;//下次數字進陣列的位置,只要size<arr.length,那麼當first已經到陣列的底部則回到頭部
		private Integer last;//佇列中出隊的位置,只要佇列中有數,則出隊last++,若++超出,則也回到頭部

		public ArrayQueue(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 Integer peek() {
			if (size == 0) {
				return null;
			}
			return arr[first];
		}

		public void push(int obj) {
			if (size == arr.length) {
				throw new ArrayIndexOutOfBoundsException("The queue is full");
			}
			size++;
			arr[last] = obj;
			last = last == arr.length - 1 ? 0 : last + 1;
		}

		public Integer poll() {
			if (size == 0) {
				throw new ArrayIndexOutOfBoundsException("The queue is empty");
			}
			size--;
			int tmp = first;
			first = first == arr.length - 1 ? 0 : first + 1;
			return arr[tmp];
		}
	}