前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >225. Implement Stack using Queues(Stack-Easy)

225. Implement Stack using Queues(Stack-Easy)

作者头像
Jack_Cui
发布2018-01-08 16:10:38
4330
发布2018-01-08 16:10:38
举报
文章被收录于专栏:Jack-CuiJack-Cui

Implement the following operations of a stack using queues.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • empty() – Return whether the stack is empty.

Notes:

  • You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

题目: 使用队列实现栈。只能使用一些简单的队列操作,例如push(x)、pop()、top()、empty()。我是使用一个队列实现一个栈。

Language:cpp

代码语言:javascript
复制
class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {
    }

    queue<int> que;      

    /** Push element x onto stack. */
    void push(int x) {
        que.push(x);
        for(int i=0; i< que.size()-1; i++){
            que.push(que.front());
            que.pop();
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int i = que.front();
        que.pop();
        return i;
    }

    /** Get the top element. */
    int top() {
        return que.front();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return que.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * bool param_4 = obj.empty();
 */
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-03-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档