转载

Java 栈(Stack)的数据实现方式

public class StackOfArray<E> implements Iterable<E> {

	private E[] item = (E[]) new Object[16];
	private int N = 0;

	private void reSize(int max) {
		E[] temp = (E[]) new Object[max];
		for (int i = 0; i < N; i++) {
			temp[i] = item[i];
		}
		item = temp;
	}

	private void push(E t) {
		if (item.length == N) {
			reSize(2 * item.length);
		}
		item[N++] = t;

	}

	private E pop() {
		E t = item[--N];
		item[N] = null;
		if (N > 0 && N == item.length / 4)
			reSize(item.length / 2);
		return t;
	}

	private E peek() {
		int i = N;
		return item[--i];
	}

	private boolean isEmpty() {
		return N == 0;
	}

	private int size() {
		return N;
	}

	@Override
	public Iterator<E> iterator() {

		return new ArrayIterator();
	}

	class ArrayIterator implements Iterator<E> {
		int i = N;

		@Override
		public boolean hasNext() {

			return i > 0;
		}

		@Override
		public E next() {
			return item[--i];
		}

	}

	public static void main(String[] args) {
		StackOfArray<String> stact = new StackOfArray<>();
		stact.push("A");
		stact.push("W");
		stact.push("E");
		stact.push("R");
		System.out.println(stact.peek());
		System.out.println(stact.pop());
		System.out.println("" + stact.isEmpty());
		System.out.println("" + stact.size());
		Iterator<String> it = stact.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}

}

复制代码
原文  https://juejin.im/post/5b9666b4e51d450e411521dd
正文到此结束
Loading...