一般而言,用队列实现栈,需要两个队列,具体就不介绍了,可以看下面这篇:
https://blog.youkuaiyun.com/qq_40927789/article/details/79955545
同理,利用栈实现队列,也需要两个栈。
利用递归以后,只需要一个栈就可以实现队列了,或者只需要一个队列就可以实现栈。
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<queue>
#include<stack>
using namespace std;
queue<int>q; //push front pop
stack<int>b; //push top pop
void stackbyqueue() //这里的递归相当于是栈,就是相当于把队列的数据存到栈中去 同理,也可以利用一个栈加上递归实现栈到队列的转换
{
while (q.size() != 0)
{
int x = q.front();
q.pop();
stackbyqueue();
cout << x << ' ';
}
}
void queuebystack() {
while (b.size() != 0)
{
int x = b.top();
b.pop();
queuebystack();
cout << x << ' ';
}
}
int main()
{
for (int i = 0; i < 5; i++)
q.push(i);
cout << "队列的顺序:";
for (int i = 0; i < 5; i++) {
int a = q.front();
q.pop();
cout <