基本介绍
代码实现(使用数组模拟)
public class ArrayStackDemo { public static void main(String[] args) { ArrayStack arrayStack = new ArrayStack(6); char key; Scanner scanner = new Scanner(System.in); a:while (true) { try { System.out.println("q:退出程序"); System.out.println("s:查看栈"); System.out.println("a:向栈中加值"); System.out.println("g:从栈中取值"); key = scanner.next().charAt(0); switch (key) { case ‘s‘: arrayStack.show(); break; case ‘a‘: System.out.println("输入一个值:"); arrayStack.push(scanner.nextInt()); break; case ‘g‘: try { System.out.println("从栈中取出的值为" + arrayStack.pop()); } catch (Exception e) { System.out.println(e.getMessage()); } break; case ‘q‘: scanner.close(); System.out.println("退出程序"); break a; default: System.out.println("命令错误"); } } catch (Exception e) { System.out.println(e.getMessage()); } } } } // 数组模拟栈 class ArrayStack{ private int maxSize; // 栈大小 private int[] stack; // 存储栈中元素 private int top = -1; // 栈顶的指针 默认-1为空 public ArrayStack(int maxSize) { this.maxSize = maxSize; stack = new int[this.maxSize]; } // 判断栈空 public boolean isEmpty() { return -1 == top; } // 判断栈满 public boolean isFull() { return top == maxSize-1; } // 向栈中加入元素 public void push(int value) { if (isFull()) { System.out.println("栈满"); return; } stack[++top] = value; } // 在栈中取元素 public int pop() { if (isEmpty()) { throw new RuntimeException("栈空"); } return stack[top--]; } // 显示栈中元素 需要从栈顶显示 public void show() { for (int i = top; i >= 0; i--) { System.out.printf("[%d]=%d\n", i, stack[i]); } } }
原文:https://www.cnblogs.com/xiaokantianse/p/13589210.html