https://leetcode.com/problems/implement-queue-using-stacks
使用堆栈实现队列。
使用两个堆栈,push的时候正常放入堆栈1,pop的时候,如果堆栈2为空,就把堆栈1的数据全部放入堆栈2(此时数据就倒序了),这时候从堆栈2的顶部就能取到最早进入的数据。
class MyQueue { public: stack<int> s1; stack<int> s2; /** Initialize your data structure here. */ MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { s1.push(x); } /** Removes the element from in front of queue and returns that element. */ int pop() { int res = peek(); s2.pop(); return res; } /** Get the front element. */ int peek() { if(s2.empty()) { while(!s1.empty()) { s2.push(s1.top()); s1.pop(); } } return s2.top(); } /** Returns whether the queue is empty. */ bool empty() { return s1.empty() && s2.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(); */