AcWing 20. 用两个栈实现队列
原题链接
简单
作者:
小笨比
,
2021-03-12 02:33:52
,
所有人可见
,
阅读 429
思路
- 由于栈是先进后出,把栈中的元素出栈再压入另一栈中,就相当于把原栈中元素换了个顺序,原栈中先进的元素在另一栈中先出了,就符合队列的规则了。
C++代码
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> s1, s2;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
}
//将s1中的元素弹出,压入s2中
void copy(stack<int> &s1, stack<int> &s2)
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
copy(s1, s2);
int t = s2.top();
s2.pop();
copy(s2, s1);
return t;
}
/** Get the front element. */
int peek() {
copy(s1, s2);
int t = s2.top();
copy(s2, s1);
return t;
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/