232. 用栈实现队列 【一个栈存输入,一个栈存输出】

15 阅读1分钟

232. 用栈实现队列

class MyQueue:

    def __init__(self):
        self.stack1 = [] # 存储
        self.stack2 = [] # 辅助

    def push(self, x: int) -> None:
        self.stack1.append(x)

    def pop(self) -> int:
        r = self.peek()  ### 重要
        self.stack2.pop()
        return r

    def peek(self) -> int:
        if self.stack2:
            return self.stack2[-1]
        if not self.stack1: return -1
        while self.stack1:
            self.stack2.append(self.stack1.pop())

        return self.stack2[-1]

    def empty(self) -> bool:
        return not self.stack1 and not self.stack2



# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

image.png

class MyQueue {
    stack<int> stackIn, stackOut;
public:
    MyQueue() {

    }
    
    void push(int x) {
        stackIn.push(x);
    }
    
    int pop() {
        int r = this->peek();
        stackOut.pop();
        return r;
    }
    
    int peek() {
        if (!stackOut.empty()){
            return stackOut.top();
        }
        if (stackIn.empty()){
            return -1;
        }else{
            while (!stackIn.empty()){
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
            return stackOut.top();
        }
    }
    
    bool empty() {
        return stackIn.empty() && stackOut.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();
 */