LeetCode 225.用队列实现栈

使用队列实现栈的下列操作:

push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空

注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-stack-using-queues

class MyStack {

    private LinkedList<Integer> linkedList = new LinkedList<Integer>();
    /** Initialize your data structure here. */
    public MyStack() { }

    /** Push element x onto stack. */
    public void push(int x) {
        linkedList.addFirst(x);
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return linkedList.removeFirst();
    }

    /** Get the top element. */
    public int top() {
        return linkedList.getFirst();
    }

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

相关阅读更多精彩内容

  • 题目地址:https://leetcode-cn.com/problems/implement-stack-usi...
    monkey01阅读 2,548评论 0 1
  • 题目描述 使用队列实现栈的下列操作: push(x) -- 元素 x 入栈 pop() -- 移除栈顶元素 top...
    云胡同学阅读 3,957评论 0 0
  • 一、题目描述 二、思路 声明两个队列解决:queue q1用于存储元素;queue q2用于辅助操作。push...
    BORN_FREE阅读 876评论 0 0
  • 今天的托管课,我和星期二一样去参加田径队选拔,这次的心情,没上次紧张了,这次我是在前七个,今天我们是跑100...
    王者荣耀大神阅读 2,990评论 0 1
  • 今天干了什么? 今天第一天上班,九点到公司集合,看了会手机,领导来了,说了当天每个小队的工作,然后开始培训 三点收...
    思涵1998阅读 1,274评论 1 0

友情链接更多精彩内容