已知Q是一个非空顺序队列,S是一个顺序栈,请设计一个算法,实现将队列Q中所有元素逆置
Q出队列一个元素,此元素再入栈S,队列出空后,开始依次弹栈,这样原队列就逆置了
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
int main()
{
stack<int> s;
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
while (!q.empty()) {
cout << q.front() << " ";
s.push(q.front());
q.pop();
}
cout << endl;
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
return 0;
}
队列特性,fifo,反向访问存入新队列即可