1.如何仅用队列结构实现占结构
例:涉及两个队列,q1输出队列元素,q2保存为输出元素,每次出队操作直到队列中仅剩一个元素时输出
#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.如何仅仅用栈实现队列结构
取两个栈分别存入取出操作即可实现
例代码:
#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;
}