思路已经在代码中
#include <iostream>
#include<queue>
#include<stack>
using namespace std;
class Q {
private:
stack<int> s1;
stack<int> s2;
public :
void push(const int& x) {
s1.push(x);//添加元素时先把元素缓存在s1中
}
int front() {
int x=0;//取出元素时,一般要先把s1中的元素全部倒入s2中,取元素是在s2中获取
if (!s1.empty()) {//当你需要取出元素
while (!s1.empty()) {//把s1栈中所有元素倒入s2中,利用栈的逆置元素的特性就能实现队列的作用
x = s1.top();
s1.pop();
s2.push(x);
}
x = s2.top();
return x;
}
else {
if (!s2.empty()) {//如果s1栈已经空了,那么直接从s2中取出元素即可
x = s2.top();
return x;
}
else {
throw exception("你不能对空队列取元素\n");
}
}
}
void pop() {
if (!s2.empty()) {
s2.pop();
}
}
};
int main()
{
Q q;
q.push(1);
q.push(2);
q.push(3);
cout << q.front() << " ";
q.pop();
cout << q.front() << " ";
q.pop();
cout << q.front() << " ";
q.push(4);
cout << q.front() << " ";
q.pop();
return 0;
}