-
基本介绍
-
代码实现(使用数组模拟)
-
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]); } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。