package com.sunny.stack;
/** * 栈 * @author zhangdong */ public class MyStack<T> { /*栈顶元素的位置**/ private int top; /*栈的容量**/ private int stackCapacity; /*存放栈中元素的数组**/ private Object[] stack; public MyStack(int stackCapacity){ this.stackCapacity = stackCapacity; top = 0; stack = new Object[stackCapacity]; } /** *判断栈是否为空 */ private boolean isEmpty(){ return top == 0; } /** * 判断栈是否是满的 * @return */ private boolean isFull(){ return top == stackCapacity; } /** * 清空栈中的元素 */ public void clearStack(){ top = 0; } /** * 获得栈中元素的个数 * @return */ public int getStackSize(){ return top; } /** * 入栈 * @return */ public boolean push(T element){ if (isFull()) { return false; } stack[top++] = element; return true; } /** * 出栈 * @return */ public T pop(){ if (isEmpty()) { return null; } T element = (T)stack[–top]; return element; } /** * 遍历栈中的元素(从栈底到栈顶) */ public void traversalStack(){ for(int i=0;i<top;i++){ if (i == top-1){ System.out.print(stack[i]); break; } System.out.print(stack[i]+”,”); } } }