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()); } } } 复制代码
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。