用数组实现 Stack 发表于 2017-09-13 | 更新于 2019-12-19 | 分类于 Algorithms | | 阅读次数 在一些面试题中,常常出现用数组实现 Stack,主要实现它的 push()/push()/pop() 方法。也可以用容器(List)和链表实现,可以看 这篇博文。以下是使用数组实现 Stack: public class StackTest { public static void main(String[] args) { ArrayStack stack = new ArrayStack(10); System.out.println("isEmpty: " + stack.isEmpty()); for (int i = 0; i < 10; i++) { stack.push(i); } System.out.println("isFull: " + stack.isFull()); System.out.println("thePeek: " + stack.peek()); while (!stack.isEmpty()) { System.out.println(stack.pop()); } }}class ArrayStack { private int[] array; private static int top;// 相当于栈顶指针 public ArrayStack(int size) { array = new int[size]; top = -1; } boolean isEmpty() { return top == -1; } boolean isFull() { return array.length - 1 == top; } // 入栈 void push(int element) { if (isFull()) { System.out.println(" 栈已满 "); } array[++top] = element;// 注意此处是 ++top } // 弹栈 int pop() { if (isEmpty()) { System.out.println(" 栈为空 "); } return array[top--]; } // 查看栈顶元素 int peek() { return array[top]; }} 个人公众号 本文作者: Depp Wang 本文链接: https://depp.wang/2017/09/13/implementing-stack-with-arrays/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!