数组栈

利用数组实现栈

代码实现

  1. import java.util.Scanner;
  2. /**
  3. * @author laoduan
  4. * @create 2020-04-10-17:21
  5. */
  6. public class ArrayStackDemo {
  7. public static void main(String[] args) {
  8. Arraystack stack = new Arraystack(4);
  9. String key = "";
  10. boolean loop = true;
  11. Scanner scanner = new Scanner(System.in);
  12. while (loop){
  13. System.out.println("------------------------");
  14. System.out.println("show:显示栈");
  15. System.out.println("exit:退出程序");
  16. System.out.println("pop:出栈");
  17. System.out.println("push:入栈\n");
  18. System.out.println("输入你的选择\n");
  19. key = scanner.next();
  20. switch (key){
  21. case "show":
  22. stack.list();
  23. break;
  24. case "push":
  25. System.out.println("请输入一个数");
  26. int value = scanner.nextInt();
  27. stack.push(value);
  28. break;
  29. case "pop":
  30. try {
  31. stack.pop();
  32. }catch (Exception e){
  33. System.out.println(e.getMessage());
  34. }
  35. break;
  36. case "exit":
  37. scanner.close();
  38. loop=false;
  39. break;
  40. default:
  41. break;
  42. }
  43. }
  44. System.out.println("程序退出");
  45. }
  46. }
  47. class Arraystack{
  48. private int maxSize;//栈的大小
  49. private int[] stack;//数组
  50. private int top = -1;
  51. public Arraystack(int maxSize){
  52. this.maxSize=maxSize;
  53. stack=new int [this.maxSize];
  54. }
  55. //栈满
  56. public boolean isFull(){
  57. return top==maxSize-1;
  58. }
  59. //栈空
  60. public boolean isEmpty(){
  61. return top==-1;
  62. }
  63. //入栈
  64. public void push(int value){
  65. if(isFull()){
  66. System.out.println("栈满,不能入栈");
  67. return;
  68. }
  69. top++;
  70. stack[top]=value;
  71. }
  72. //出栈
  73. public int pop(){
  74. if (isEmpty()){
  75. throw new RuntimeException("栈空");
  76. }
  77. top--;
  78. return stack[top+1];
  79. }
  80. //遍历栈
  81. public void list(){
  82. if (isEmpty()){
  83. System.out.println("栈空,不能遍历");
  84. }
  85. for (int i=top;i>-1;i--){
  86. System.out.printf("stacl[%d]=%d\n",i,stack[i]);
  87. }
  88. }
  89. }