一、栈
/** * 自定义栈:后进先出 */ public class Stack<T> { private final int length=10; private final Object[] entry = new Object[length]; private int top = -1; /** * top==-1是栈为空 * @return */ public boolean isEmpty() { return top == -1; } /** * top=0~9代表栈的十个元素,所以top==9代表栈已满 * @return */ public boolean isFull() { return top==length-1; } /** * 入栈 * @param x */ public void push(T x) { if (isFull()) { throw new IndexOutOfBoundsException("栈已满"); } top = top + 1; entry[top] = x; } /** * 出栈 * @return */ public T pop() { if (isEmpty()) { throw new IndexOutOfBoundsException("栈为空"); } top = top - 1; return (T) entry[top+1]; } public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); System.out.println(stack.isEmpty()); for (int i = 0; i < 10; i++) { System.out.println(i); stack.push(i); } System.out.println(stack.pop()); } }