实现一个简单栈

实现 - 栈

栈的实现比队列容易。动态数组足以实现堆栈结构。

class MyStack {
    private List<Integer> data;  // store elements
    public MyStack() {
        data = new ArrayList<>();
    }
    /** Insert an element into the stack. */
    public void push(int x) {
        data.add(x);
    }
    /** Checks whether the queue is empty or not. */
    public boolean isEmpty() {
        return data.isEmpty();
    }
    /** Get the top item from the queue. */
    public int top() {
        return data.get(data.size() - 1);
    }
    /** Delete an element from the queue. Return true if the operation is successful. */
    public Integer  pop() {
        if (isEmpty()) {
            return null;
        }
        Integer pop = data.get(data.size() - 1);
        data.remove(data.size() - 1);
        return pop;
    }
    public static void main(String[] args) {
        MyStack s = new MyStack();
        s.push(1);
        s.push(2);
        s.push(3);
        for (int i = 0; i < 4; ++i) {
            System.out.println(s.pop());
        }
    }
}

3
2
1
null

总结

栈是一种先进后出(LIFO)的数据结构。与队列类似,总是在堆栈的末尾添加一个新元素。但是,删除操作,退栈 pop ,将始终删除队列中相对于它的最后一个元素。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 栈 栈的英文单词是Stack,它代表一种特殊的线性表,这种线性表只能在固定一端(通常认为是线性表的尾端)进行插入,...
    Jack921阅读 1,661评论 0 5
  • ⦁ 数据结构 数据结构是计算机存储和组织数据的的方式 1. 数组 在Java中,数组是用来存放同一种数据类型的集合...
    欲火逢生阅读 592评论 0 3
  • 如需转载, 请咨询作者, 并且注明出处.有任何问题, 可以关注我的微博: coderwhy, 或者添加我的微信: ...
    coderwhy阅读 20,280评论 5 49
  • 栈结构 栈也是一种非常常见的数据结构, 并且在程序中的应用非常广泛. 一. 认识栈结构 我们先来简单认识一下栈结构...
    小码哥教育520it阅读 2,012评论 0 1
  • 这几天事有点多,不知道怎么了。就觉得整个人很烦躁,工作也好,生活也罢,都不是很顺利。 这几天看完了“解忧杂货店”,...
    悦读悦动阅读 233评论 0 0

友情链接更多精彩内容