232.用栈实现队列

在这里插入图片描述

class MyQueue {
    
    
public:
    stack<int> stack1;
    stack<int> stack2;
    /** Initialize your data structure here. */
    MyQueue() {
    
    
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
    
    
        stack1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
    
    
        if(stack2.empty())
        {
    
    
            while(!stack1.empty())
            {
    
    
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        int result = stack2.top();
        stack2.pop();

        while(!stack2.empty())
        {
    
    
            stack1.push(stack2.top());
            stack2.pop();
        }
        return result;
    }
    
    /** Get the front element. */
    int peek() {
    
    
        if(stack2.empty())
        {
    
    
            while(!stack1.empty())
            {
    
    
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        int result=stack2.top();
        while(!stack2.empty())
        {
    
    
            stack1.push(stack2.top());
            stack2.pop();
        }
        return result;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
    
    
        if(stack1.empty()&&stack2.empty())
            return true;
        else 
            return false;
    }
};

/**
 * 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();
 */

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41363459/article/details/113802287