看到这个题,要很清楚栈和队列的执行方式,栈是先进后出,队列是先进先出。
- 将所有数进队queue1中(以1,2,3,4举例),1在队首的位置。
- 出队操作,依次从queue1中pop元素,临时队列queue2来push元素,直到剩下唯一的一个元素停止。
- 用临时变量tmp接受最后这个元素,将queue2中赋给queue1。
- 返回临时变量,依次循环上述步骤。
#include<stack>
#include<queue>
#include<iostream>
using namespace std;
class queueStack
{
queue<int> m_qu1;
public:
queueStack()
{
}
void push(int x)
{
m_qu1.push(x);
}
void pop()
{
queue<int> m_qu2;
while (m_qu1.size() > 1)
{
m_qu2.push(m_qu1.front());
m_qu1.pop();
}
m_qu1 = m_qu2;
}
int top()
{
queue<int> m_qu2;
while (m_qu1.size() > 1)
{
m_qu2.push(m_qu1.front());
m_qu1.pop();
}
int tmp = m_qu1.front();
m_qu2.push(m_qu1.front());
m_qu1 = m_qu2;
return tmp;
}
};
int main()
{
queueStack qs;
qs.push(1);
qs.push(2);
qs.push(3);
qs.push(4);
cout << qs.top() << endl;
qs.pop();
cout << qs.top() << endl;
qs.pop();
cout << qs.top() << endl;
qs.pop();
cout << qs.top() << endl;
qs.pop();
system("pause");
return 0;
}