package com.sjtu.design.excise; //栈类 /** * * @author tsh11089 * */ public class SqStack { private Object[] stackElem; private int top; // 初始化栈 public SqStack(int maxStack) { stackElem = new Object[maxStack]; top = 0; } // 入栈 public void push(Object stack) { if (top == stackElem.length) { // throw new Exception("栈已满!"); System.out.println("栈已满!"); } else { stackElem[top++] = stack; } } // 出栈 public Object pop() { if (top == 0) { // throw new Exception("栈为空!"); System.out.println("栈为空!"); return null; } else { return stackElem[--top];// 删除然后返回现在的栈顶 } } // 打印(从栈顶到栈底) public void display() { for (int i = length() - 1; i >= 0; i--) { System.out.print(stackElem[i] + " "); } System.out.println(); } // 元素个数 public int length() { return top; } // 栈顶 public Object peek() { if (!isEmpty()) return stackElem[top - 1]; else return null; } // 清空 public void clear() { top = 0; } // 释放栈内存空间 public void free(SqStack stack) { if (stack != null) { stack = null; } } // 栈空 public boolean isEmpty() { return top == 0; } // 栈满 public boolean isFull() { return top == stackElem.length; } public static void main(String[] args) { SqStack sqStack1 = new SqStack(3); sqStack1.push(1); sqStack1.push(4); sqStack1.push(7); System.out.print("打印输出: "); sqStack1.display(); int top1 = (Integer) sqStack1.peek(); System.out.println("栈顶: " + top1); sqStack1.pop(); System.out.print("弹出栈顶,打印输出: "); sqStack1.display(); System.out.println("---------------------------------------"); SqStack sqStack2 = new SqStack(2); sqStack2.push(2); sqStack2.push(5); sqStack2.push(8); System.out.print("打印输出: "); sqStack2.display(); int top2 = (Integer) sqStack2.peek(); System.out.println("栈顶: " + top2); sqStack2.pop(); System.out.print("弹出栈顶,打印输出: "); sqStack2.display(); System.out.println("---------------------------------------"); SqStack sqStack3 = new SqStack(0); sqStack3.push(3); sqStack3.push(6); sqStack3.push(9); System.out.print("打印输出: "); sqStack3.display(); int top3 = (Integer) sqStack3.peek(); System.out.println("栈顶: " + top3); sqStack3.pop(); System.out.print("弹出栈顶,打印输出: "); sqStack3.display(); } } |
|
来自: _bolo > 《DataStructure》