思路分析
源代码实现
package stack; import java.util.Scanner; /** * @program: DataStructures * description: 用数组来模拟栈 * @author: Mr.Zhang * @create: 2020-17-07_21:17 **/ public class ArrayStackDemo { public static void main(String[] args) { // 创建最大容量为 3 的栈 ArrayStack stack = new ArrayStack(3); boolean flag = true; // 循环条件 Scanner scanner = new Scanner(System.in); while (flag) { System.out.println("入栈(i)"); System.out.println("出栈(o)"); System.out.println("显示全部(s)"); System.out.println("退出(e)"); // 接收用户输入 System.out.print("请选择功能:"); char c = scanner.next().charAt(0); System.out.println("------------------"); switch (c) { case 'i': System.out.print("请输入需要进栈的元素:"); stack.push(scanner.next().toString()); break; case 'o': try { System.out.println("出栈的元素为:" + stack.pop()); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 's': stack.showAll(); break; case 'e': flag = false; break; default: break; } } } } // 栈类 class ArrayStack { private int maxSize; //栈的最大容量 private String[] arrStack; // 存储数据的数组 private int top; //栈顶指针 // 构造函数 public ArrayStack(int maxSize) { this.maxSize = maxSize; this.arrStack = new String[maxSize]; this.top = -1; } // 判断栈是否满了 public boolean isFull() { return top == maxSize - 1; } // 判断栈是否为空 public boolean isNull() { return top == -1; } // 入栈 public void push(String s) { // 首先判断栈是否满了 if (isFull()) { System.out.println("栈已经满了,不能存数据了!!"); return; } // 栈没满 top++; arrStack[top] = s; // arrStack[++top] = s; } // 出栈 public String pop() { // 首先判断栈是否为空 if (isNull()) { throw new RuntimeException("栈为空,不能取数据!!!"); } String value = arrStack[top]; top--; return value; // return arrStack[top--]; } // 显示栈中全部元素 public void showAll() { // 首先判断栈是否为空 if (isNull()) { System.out.println("显示全部,栈为空!!"); return; } for (int i = top; i >= 0; i--) { System.out.printf("栈【%d】数据:%s\n", i, arrStack[i]); } } }