主要体现的是栈先进后出的特点
代码实现:
package Stack; import java.util.Scanner; public class ArrayStackDemo { public static void main(String[] args) { //测试ArrayStack ArrayStack stack = new ArrayStack(4); String key = ""; Scanner sc = new Scanner(System.in); boolean loop = true; while(loop){ System.out.println("show: 表示显示栈"); System.out.println("exit: 退出程序"); System.out.println("push: 表示添加数据到栈(入栈)"); System.out.println("pop: 表示从栈取出数据(出栈)"); System.out.println("请输入你的选择"); key = sc.next(); switch (key){ case "show": stack.List(); break; case "push": System.out.println("请输入一个数:"); int value = sc.nextInt(); stack.push(value); break; case "pop": try{ int result = stack.pop(); System.out.printf("出栈的顺序是:%d",result); }catch (Exception e){ System.out.println(e.getMessage()); } break; case "exit": sc.close(); loop = false;//退出循环 break; } } System.out.println("退出程序"); } } class ArrayStack{ private int maxSize; private int[] stack; private int top = -1; public ArrayStack(int maxSize){ this.maxSize = maxSize; stack = new int[this.maxSize]; } //栈满 public boolean isFull(){ return top == maxSize - 1; } //栈空 public boolean isEmpty(){ return top == -1; } //入栈 public void push(int value){ if (isFull()){ System.out.println("栈满,无法添加数据"); return; } top++; stack[top] = value; } //出栈 public int pop(){ if (isEmpty()){ throw new RuntimeException("栈空,无法出栈"); } int value = stack[top]; top--; return value; } //显示遍历栈 public void List(){ if (isEmpty()){ System.out.println("栈空,无法显示数据"); return; } for (int i = top; i >= 0; i--){ System.out.printf("stack[%d] = %dn",i,stack[i]); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)