1.1 用两个栈实现一个队列

来源:互联网 发布:steam淘宝买游戏 编辑:程序博客网 时间:2024/06/05 10:21

假设两个栈A和B,且都为空。
可以认为栈A提供入队列的功能,栈B提供出队列的功能。
入队列:入栈A。
出队列:
● 如果栈B不为空,直接弹出栈B的数据。
● 如果栈B为空,则依次弹出栈A的数据,放入栈B中,再弹出栈B的数据。

#include <iostream>#include <stack>using namespace std;//入队操作void pushQueue(stack<int> &a, stack<int> &b, int num){    a.push(num);}//出队操作void popQueue(stack<int> &a, stack<int> &b){    if(!b.empty())          //若栈b不为空,则直接弹出栈b的栈顶元素    {        cout<<b.top()<<endl;        b.pop();    }    else         //若栈b为空,则将栈a中元素依次入栈到b,再弹出栈b的栈顶元素    {        while(!a.empty())        {            b.push(a.top());            a.pop();        }        cout<<b.top()<<endl;        b.pop();    }}int main(){    stack<int> a, b;    pushQueue(a, b, 1);    pushQueue(a, b, 2);    pushQueue(a, b, 3);    pushQueue(a, b, 4);    popQueue(a, b);    popQueue(a, b);    popQueue(a, b);    popQueue(a, b);    return 0;}
0 0
原创粉丝点击