问题描述:
RTRT
基本思路:
- 由于栈的出入顺序是相反的,而队列的顺序是相同的。负负得正嘛。我们不妨用两个栈来实现。
- 队列中有两个栈,其中一个用于模拟入队,另一个用于模拟出队。两个栈的所有元素构成我们队列中的元素。当模拟出队的栈空间不够的时候,我们就把入队栈中所有的元素全部倒入出队栈。
- 当然我们可以用链表啥的来实现,不过这种实现方法每次取队首元素是都要遍历全表。而我们的方法只是在出队栈为空的时候才要这么做。其他时间都是O(1)。
AC代码:
#include<bits/stdc++.h>
using namespace std;
class MyQueue {
private:
stack<int> in;
stack<int> out;
public:
void FetchFromOut() {
// 把in中的元素全部转移给out
while (!in.empty()) {
int t = in.top();
in.pop();
out.push(t);
}
}
void push(int x) { in.push(x); }
int pop() {
if (out.empty()) {
FetchFromOut();
}
int ret_val = out.top();
out.pop();
return ret_val;
}
int peek() {
if (out.empty()) {
FetchFromOut();
}
return out.top();
}
bool empty() { return in.empty() && out.empty(); }
};