美文网首页
leetcode255、两个队列实现栈

leetcode255、两个队列实现栈

作者: 残剑天下论 | 来源:发表于2020-05-14 14:58 被阅读0次
#include <queue>
#include <iostream>

using namespace std;

class MyStack
{
public:
    // Initialize your data structure here.
    MyStack(){}

    // Push element x onto stack.
    void push(int x)
    {
        queue<int> temp_queue;  // 空队列
        temp_queue.push(x);
        // 将_data中所有数据依次添加到temp_queue中
        while (!_data.empty())
        {
            temp_queue.push(_data.front());
            _data.pop();
        }
        // 将temp_queue中所有数据依次添加到_data中
        while (!temp_queue.empty())
        {
            _data.push(temp_queue.front());
            temp_queue.pop();
        }
    }

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

    // Get the top element.
    int top()
    {
        int x = _data.front();
        return x;
    }

    // Returns whether the stack is empty.
    bool empty()
    {
        return _data.empty();
    }
private:
    queue<int> _data;
};


int main()
{
    MyStack S;
    S.push(1);
    S.push(2);
    S.push(3);
    S.push(4);

    S.pop();

    S.push(5);
    return 0;
}

相关文章

  • 栈和队列

    两个栈实现队列 两个队列实现栈

  • 栈&队列

    一、栈&队列总结 栈/队列的应用接雨水验证栈序列滑动窗口的最大值 栈/队列的特殊实现用两个栈实现队列用两个队列实现...

  • 队列、栈

    两个队列实现一个栈 两个栈实现一个队列

  • 面试题9: 用两个栈实现队列

    9-1 用两个栈实现队列 9-2 用两个队列实现栈

  • 手撕栈队列

    【面试题07:用两个栈实现队列】 题目:利用两个栈实现队列的插入,取队首,判断非空等函数。拓展:用两个队列实现栈,...

  • 用两个栈实现队列,用两个队列实现堆栈

    参考:剑指Offer面试题7(Java版):用两个栈实现队列与用两个队列实现栈 用两个栈实现队列stack1作为入...

  • 栈和队列的相互实现

    两个栈实现队列: 一个栈用来入,一个栈用来出 两个队列实现栈: 入栈的时候正常存入一个队列,出栈的时候用另一个队列...

  • Swift-两个栈实现队列

    题目:两个栈实现队列,栈是先入后出,队列是先入先出,两个栈可以利用这个特点实现队列. 核心代码: `class ...

  • LeetCode 每日一题 [43] 用两个栈实现队列

    LeetCode 用两个栈实现队列 [简单] 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appen...

  • 剑指Offer

    09 用两个栈实现队列 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 del...

网友评论

      本文标题:leetcode255、两个队列实现栈

      本文链接:https://www.haomeiwen.com/subject/whpcohtx.html