leetccode 225. implementing stacks (two queues analog) with a queue

Queue implementation using the following stack:

push (x) - x elements onto the stack
pop () - remove the top of the stack
top () - Gets the top element
empty () - Returns the stack is empty
Note:

You can only use the basic operation of the queue - that is, push to back, peek / pop from front, size, and is empty of these operations are legal.
The language you are using may not support queue. You can use the list or the deque (deque) to simulate a queue, the queue as long as the operation to the standard.
You may assume that all operations are valid (for example, to an empty stack does not call the pop operation or top).
Submitted by 70,324 times 45,211 times

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/implement-stack-using-queues

class MyStack {
public:
    /** Initialize your data structure here. */
    queue<int>a;
    queue<int>b;
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        b.push(x);
        while(!a.empty()){
            int y=a.front();
            b.push(y);
            a.pop();
        }
        while(!b.empty()){
            int y=b.front();
            a.push(y);
            b.pop();
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int y=a.front();
        a.pop();
        return y;
    }
    
    /** Get the top element. */
    int top() {
        return a.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return a.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

 

Guess you like

Origin www.cnblogs.com/wz-archer/p/12606959.html