两个栈实现队列

来源:互联网 发布:linux编写shell程序 编辑:程序博客网 时间:2024/06/05 04:05

问题描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

函数接口:void push(int node)
int pop()

解题方法:首先对于实现队列push的方法只需要将元素放入stack1中就可以了,对于队列pop的方法,首先判断stack2是否为空,如果为空直接将stack1中的所有元素全部弹出栈并且压入stack2中,然后将stack2栈顶元素弹出,如果stack2不为空,则直接将stack2中的栈顶元素弹出就可以了。

算法代码:

void push(int node) //进队列    {        stack1.push(node);    }    int pop() //出队列    {             int elem = 0;            if (stack2.empty())//判断stack2是否为空            {                while (!stack1.empty())                {                    stack2.push(stack1.top());                    stack1.pop();                }            }            elem=stack2.top();            stack2.pop();            return elem;    }

下面给出所有代码和测试结果

#include<iostream>#include<stack>using namespace std;class Solution{public:    void push(int node) //进队列    {        stack1.push(node);    }    int pop() //出队列    {             int elem = 0;            if (stack2.empty())//判断stack2是否为空            {                while (!stack1.empty())                {                    stack2.push(stack1.top());                    stack1.pop();                }            }            elem=stack2.top();            stack2.pop();            return elem;    }private:    stack<int> stack1;    stack<int> stack2;};int main(){    Solution s;    s.push(1);    s.push(2);    cout << s.pop();    cout << s.pop();    s.push(1);    s.push(2);    s.push(3);    cout << s.pop();    cout << s.pop();    cout << s.pop();    system("pause");    return 0;}

测试结果如下:正确应该按照队列先进先出的顺序输出12123
这里写图片描述

这道题比较简单在《栈和队列的相关面试题》中我也写过,想看关于栈和队列一些问题的可以点击下面查看
栈和队列的面试题

原创粉丝点击