The title

You can implement a first-in, first-out queue using only two stacks. Queues should support all operations supported by normal queues (push, POP, peek, empty) :

Implement MyQueue class:

Void push(int x) pushes element X to the end of the queue

Int pop() removes and returns the element from the beginning of the queue

Int peek() returns the element at the beginning of the queue

Boolean empty() Returns true if the queue is empty; Otherwise, return false

Description:

You can only use standard stack operations — that is, only push to Top, peek/ Pop from Top, size, and is empty are legal.

Your language may not support stacks. You can use a list or a deque to simulate a stack, as long as it’s standard stack operations.

Advanced:

Can you implement queues with O(1) amortized time per operation? In other words, the total time complexity of performing n operations is O(n), even though one of them may take a long time.



Look at other people’s ideas and use the double stack idea

Push data: Puts data on the input stack

Pop the data:

If the output stack is empty, all the input stack data is imported, and then the data is ejected from the output stack

If the output stack is not empty, pop data directly from the output stack.

How to tell if a queue is empty: If both the input stack and the output stack are empty, the simulated queue is empty.

code

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    /** Initialize your data structure here. */
    MyQueue() {}/** Push element x to the back of queue. */
    void push(int x) {
        stIn.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop(a) {
        // If output stack is empty
        if(stOut.empty())
        {
            // Import all data
            while(! stIn.empty())
            {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        // Pop data from the output stack
        int result =stOut.top(a); stOut.pop(a);return result;
    }
    
    /** Get the front element. */
    int peek(a) {
        // Use the existing pop function directly
        int res = this->pop(a);// Because the pop() function pops the element res, we have to add it back
        stOut.push(res);
        return res;
    }
    
    /** Returns whether the queue is empty. */
    bool empty(a) {
        return stIn.empty() && stOut.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(); * /
Copy the code