[LeetCode]232. Implement Queue using Stacks

来源:互联网 发布:三维编程叫什么 编辑:程序博客网 时间:2024/05/16 07:17

[LeetCode]232. Implement Queue using Stacks

题目描述

这里写图片描述

思路

两个栈实现

代码

#include <iostream>#include <stack>using namespace std;class MyQueue {public:    /** Initialize your data structure here. */    MyQueue() { }    /** 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 res = peek();        if (output.size()) {            output.pop();        }        return res;    }    /** Get the front element. */    int peek() {        if (output.empty()) {            while (input.size()) {                output.push(input.top());                input.pop();            }        }        if(output.size())            return output.top();        return 0;    }    /** Returns whether the queue is empty. */    bool empty() {        return input.empty() && output.empty();    }private:    stack<int> input, output;};int main() {    MyQueue obj;    int param_2 = obj.pop();    int param_3 = obj.peek();    bool param_4 = obj.empty();    cout << param_2 << " " << param_3 << " " << param_4 << endl;    system("pause");    return 0;}
0 0
原创粉丝点击