4.1、顺序栈的实现(java实现)
1、实现源码
public class SeqStack { private final int MaxSize = 8; private int top; //栈顶 private Object stack[]; /** * 初始化 */ public SeqStack() { this.top = 0; this.stack = new Object[MaxSize]; } /** * 是否为空 * @param seqStack :要判断的堆栈 * @return true :空 false:未空 */ private boolean isEmpty(SeqStack seqStack){ if (seqStack.top <= 0){ return true; } return false; } /** * 是否已满 * @param seqStack :要判断的堆栈 * @return : true :满 false:空 */ private boolean isFull(SeqStack seqStack){ if (seqStack.top >= MaxSize){ return true; } return false; } /** *入栈 * @param seqStack :要入栈的堆栈 * @param element :入栈数据 */ private void stackPush(SeqStack seqStack,Object element){ if (isFull(seqStack)){ System.out.println("堆栈已满无法插入"); return; } seqStack.stack[seqStack.top] = element; System.out.println(element + " 已入栈"); seqStack.top++; } /** * 出堆栈 * @param seqStack : 要出栈的堆栈 */ private void stackPop(SeqStack seqStack){ if (isEmpty(seqStack)){ System.out.println("空堆栈无可出的元素"); return; } seqStack.top--; System.out.print(seqStack.stack[seqStack.top] + " "); } /** * 取栈顶元素 * @param seqStack :要取栈顶元素的堆栈 */ private void stackTop(SeqStack seqStack){ if (isEmpty(seqStack)){ System.out.println("空堆栈,无栈顶元素"); return; } System.out.println("取栈顶元素值 :"+ seqStack.stack[seqStack.top - 1]); } public static void main(String[] args) { SeqStack seqStack = new SeqStack(); seqStack.stackPop(seqStack); seqStack.stackTop(seqStack); for (int i = 0; i < 9; i++) { seqStack.stackPush(seqStack,i); } seqStack.stackTop(seqStack); int number = seqStack.top; System.out.print("元素出栈: "); for (int i = 0; i < number; i++) { seqStack.stackPop(seqStack); } } }
2、测试结果
空堆栈无可出的元素 空堆栈,无栈顶元素 0 已入栈 1 已入栈 2 已入栈 3 已入栈 4 已入栈 5 已入栈 6 已入栈 7 已入栈 堆栈已满无法插入 取栈顶元素值 :7 元素出栈: 7 6 5 4 3 2 1 0