我有一个问题一开始没反应过来,就是s2的栈顶一定是队列队头的。如果s2空了,s1会把全部元素转到s2
#include<iostream>
#include<stack>
using namespace std;
class MyQueue {
private:
stack<int>s1, s2;
void intoout() {
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
public:
MyQueue() {}
void push(int x) {
s1.push(x);
}
int pop() {
if (s2.empty()) {
intoout();
}
int x = s2.top();
s2.pop();
return x;
}
int peek() {
if (s2.empty()) {
intoout();
}
int x = s2.top();
return x;
}
bool empty() {
return s1.empty() && s2.empty();
}
};
int main() {
MyQueue* obj = new MyQueue();
obj->push(1);
obj->push(2);
cout << obj->pop();
cout << obj->peek();
cout << obj->empty();
}