剑指Offer面试题7[用两个栈实现队列]

来源:互联网 发布:pg数据库如何导入数据 编辑:程序博客网 时间:2024/06/06 08:42

1.题目描述:

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

2. 相关知识:

  栈是先进后出,队列是先进先出

3. 解答思路:

  插入操作始终往一个栈中插入,弹出操作则从一个栈压入另一个栈,再从另一个栈中弹出,从而实现了先进先出。

4. 代码实现:

#include <stdio.h>#include "stdafx.h"#include <stack>  using namespace std;class Solution{public:    void push(int node) {        stack1.push(node);    }    int pop() {        if (stack2.size() <= 0)//stack2为空,则将stack1中的数据全部压入stack2        {            while (stack1.size()>0)            {                stack2.push(stack1.top());                stack1.pop();            }                   }        if (stack2.size() == 0)                 printf("queue is empty!");        int head = stack2.top();        stack2.pop();        return head;    }private:    stack<int> stack1;    stack<int> stack2;};int _tmain(int argc, _TCHAR* argv[]){    Solution s;    s.push(1);    s.push(2);    s.push(3);    s.pop();    return 0;}
原创粉丝点击