LeetCode 232.Implement Que using Stocks--2つのスタックで1つの列--C++解法を実現します。


LeetCode 232.Implement Que using Stocks–C++解法
LeetCodeの題目コラム:LeetCodeは私のしたすべてのLeetCodeのテーマをこのコラムに書いています。ほとんどのテーマはJavaとPythonの解法です。
タイトル住所:Implement Que using Stock-LeetCode
Implement the follwing operations of a queue using stacks.
push(x)–Push element x to the back of queue.pop()–Removes the element from in from of queue.peek()–Get the front element.empy()–Return whethe the queue emit.Example:
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 pussh to p,peek/pop from top,size,and is emipty operations are valid.Depending on your lagge,stack may not supported native.Youquemute.Youquene。as long as you use only standard operations of a stack.You may asume that all operations are valid(for example、no pop or peek operations will be caled on an empy queue)
このテーマは2つのスタックで一つの列を実現し、入隊と出隊までの時間の複雑さはO(1)である。
C++の解法は以下の通りです
class MyQueue {
public:
    stack<int> inbox, outbox;

    /** Initialize your data structure here. */
    MyQueue() {
        ;
    }

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

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int temp = peek();
        outbox.pop();
        return temp;
    }

    /** Get the front element. */
    int peek() {
        cout << outbox.empty() << endl;
        if (outbox.empty() == 1) {
            while (inbox.empty() == 0) {
                outbox.push(inbox.top());
                inbox.pop();
            }
        }
        return outbox.top();
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return inbox.empty() && outbox.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();
 */