C++版 - 剑指offer 面试题7:用两个栈实现队列 题解

用两个栈实现队列




参与人数:6484  时间限制:1秒   空间限制:32768K

本题知识点: 队列


用两个栈实现一个队列的功能?请给出算法和思路!

<分析>:

入队:将元素进栈A

出队:判断栈B是否为空,如果为空,则将栈A中的每个元素pop,并push进栈B,取出栈B的顶端值并将其返回,如果不为空,栈B直接出栈。


同理:

用两个队列实现一个栈的功能?

<分析>:

入栈:将元素进队列A

出栈:判断队列A中元素的个数是否为1,如果等于1,则出队列;否则将队列A中的元素,依次出队列并放入队列B,直到队列A中的元素只留下一个,然后队列A出队列,再把队列B中的元素出队列依次放入队列A中。


AC代码:

#include<iostream>
#include<stack>
#include<ctime>
using namespace std;

class Solution
{
private:
    stack<int> stack1;
    stack<int> stack2;
public:
    void push(int node)
	{
       stack1.push(node);
    }

    int pop()
	{
        int tempVal;
        if(stack2.empty()){
            while(!stack1.empty()){
                tempVal=stack1.top();
                stack2.push(tempVal);
                stack1.pop();
            }
        }
        tempVal=stack2.top();
        stack2.pop();
        return tempVal;
    }
};

// 以下为测试部分,加入了随机数
/*
int main()
{
	Solution sol;

    srand((unsigned)time(NULL));
    rand();
    double feed=((double) rand()/(RAND_MAX)) + 1;  // 产生真正的随机数

	for(int idx=1;idx<=5;idx++)
	{
		sol.push(3.24*idx*feed);
	}
		cout<<sol.pop()<<endl;
		cout<<sol.pop()<<endl;
		cout<<sol.pop()<<endl;
		cout<<sol.pop()<<endl;
		cout<<sol.pop()<<endl;  // 由于新的队列中没有top()函数,但pop()函数有返回值,故可以如此操作
	return 0;
}
*/

另外,有博友用template实现了相关功能: http://blog.csdn.net/xiaofei2010/article/details/8922497


posted @ 2016-04-21 22:53  大白技术控  阅读(307)  评论(0编辑  收藏  举报