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

232.Implement Queue using Stacks(Stack-Easy)

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

Implement the following operations of a queue using stacks.

  • push(x) – Push element x to the back of queue.
  • pop() – Removes the element from in front of queue.
  • peek() – Get the front element.
  • empty() – Return whether the queue is empty.

Notes:

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

题目: 用Stacks实现Queue。

思路: Queue是先进先出FIFO,Stack是先进后出FILO。使用Stack模拟实现Queue的功能,可以使用两个Stack,一个进行入Stack操作,一个进行出Stack操作。这两个Stack中的元素位置是颠倒的。比如,一个元素在第一个Stack位于Stack头,那么这个元素在另一个Stack则位于Stack尾。

Language : cpp

代码语言:javascript
复制
class MyQueue {
public:

    stack<int> input, output;
    /** Push element x to the back of queue. */
    void push(int x) {
        input.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int a = peek();
        output.pop();
        return a;
    }

    /** Get the front element. */
    int peek() {
        if(output.empty()){
            while(input.size()){
                output.push(input.top());
                input.pop();
            }
        }
        return output.top();
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return input.empty() && output.empty();
    }
};

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

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

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

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

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