2021年3月5日每日一题
原题:232. 用栈实现队列
这道题就是字面意思,用栈来模拟队列
栈:先入后出
队列:先入先出
维护两个栈,一个负责接收,一个负责输出
这道题其实可以用vector来模拟也是一样的
c++代码如下:
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int>a,b;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
a.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int ans = this->peek();
b.pop();
return ans;
}
/** Get the front element. */
int peek() {
if(b.empty()){
while(!a.empty()){
b.push(a.top());
a.pop();
}
}
return b.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return a.empty() && b.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();
*/
结果