[数据结构]-数组实现栈
package com.cn.jichu.day08; public class Stack<E> { /** * 数组 */ private E[] data; /** * 当前容纳元素个数 */ private int size; /** * 指针 */ private int pointer; public Stack(int capacity) { data = (E[])new Object[capacity]; size = capacity; pointer = 0; } public Stack() { this(10); } /** * 入栈 * @param e */ public void push(E e){ if(pointer == size){ throw new IllegalArgumentException("大哥,栈要溢出来了"); } data[pointer] = e; pointer ++; } /** * 出栈 * @return */ public E pop(){ if(pointer==0){ throw new IllegalArgumentException("大哥,栈中无元素哟"); } E e = data[pointer-1]; data[pointer-1] = null; pointer --; return e; } /** * 获取栈顶元素 * @return */ public E peek(){ if(pointer==0){ throw new IllegalArgumentException("大哥,栈中无元素哟"); } E e = data[pointer-1]; return e; } @Override public String toString(){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Stack ["); for(int i=0;i<data.length;i++){ stringBuilder.append(data[i] + " "); } stringBuilder.append("]"); return stringBuilder.toString(); } }
Don't stop!Never give up!