1. How to structure accounts for only queue structure to achieve
Example: involving two queues, q1 output queue element, an output element q2 is stored, each dequeue the queue until a remaining output element
#include <cstdio>
#include <queue>
using namespace std;
int main()
{
queue<int> q1, q2;
for (int i = 1; i <= 5; i++)
{
q1.push(i);
printf("%d ", i);
}
printf("\n");
while (q1.size() > 0)//开始实现栈功能
{
while (q1.size() > 1)//将q1中q.size()-1个元素存入q2中
{
q2.push(q1.front());
q1.pop();
}
printf("%d ", q1.front());//输出q1中最后一个元素
q1.pop();//q1置为空
while (!q2.empty())//将q2中的所有元素还原到q1中
{
q1.push(q2.front());
q2.pop();
}
}
return 0;
}
2. How to implement only the queue structure with a stack
Are stored in two stacks take out operation can be realized
Code Example:
#include <cstdio>
#include <stack>
using namespace std;
int main()//栈实现队列
{
stack<int> st1, st2;
for (int i = 1; i <= 5; i++)
{
st1.push(i);
printf("%d ", i);
}
printf("\n");
while (!st1.empty())
{
st2.push(st1.top());
st1.pop();
}
while (!st2.empty())
{
printf("%d ", st2.top());
st2.pop();
}
system("pause");
return 0;
}