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

LeetCode 0232 - Implement Queue using Stacks

作者头像
Reck Zhang
发布2021-08-11 12:01:30
2010
发布2021-08-11 12:01:30
举报
文章被收录于专栏:Reck Zhang

Implement Queue using Stacks

Desicription

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.

Example:

代码语言:javascript
复制
MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // returns 1
queue.pop();   // returns 1
queue.empty(); // returns false

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).

Solution

代码语言:javascript
复制
/**
 * 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();
 */

class MyQueue {
private:
    stack<int> stackPush, stackPop;
public:
    /** Initialize your data structure here. */
    MyQueue() {

    }

    /** Push element x to the back of queue. */
    void push(int x) {
        stackPush.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if(stackPop.empty()) {
            while(!stackPush.empty()) {
                int temp = stackPush.top();
                stackPush.pop();
                stackPop.push(temp);
            }
        }
        int result = stackPop.top();
        stackPop.pop();
        return result;
    }

    /** Get the front element. */
    int peek() {
        if(stackPop.empty()) {
            while(!stackPush.empty()) {
                int temp = stackPush.top();
                stackPush.pop();
                stackPop.push(temp);
            }
        }
        return stackPop.top();
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return stackPop.empty() && stackPush.empty();
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-08-17,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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