剑指offer——用两个栈实现队列

题目描述

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

开始思路有个误区,觉得压入时所有元素必须在stack1里面,弹出时所有元素必须在stack2里面。其实弹出时只要stack2非空,直接从stack2弹出就好了,栈顶就是最先进入队列的元素,为空,再把stack1所有元素一个个弹出并压入stack2。压入的话直接push进stack1就行了。

#include<exception>
using namespace std;
class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        int temp;
        if(!stack2.empty())
        {
            temp = stack2.top();
            stack2.pop();
        }    
        else if(!stack1.empty())
        {
            while(!stack1.empty())
            {
                stack2.push(stack1.top());
                stack1.pop();
            } 
            temp = stack2.top();
            stack2.pop();
        }
        //else
           // throw new exception("quene is empty");
        return temp;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

调错总结:

(1)开始没有看到pop()返回值是int,以为是void,没有return pop出来的元素,报下面这个错误:

error: control reaches end of non-void function [-Werror,-Wreturn-type]

就是该有返回值的地方没有取得返回值的意思。

(2)当stack1和stack2都为空的时候,pop操作可以抛出一个异常,但是加上书上相应代码之后报错:

error: no matching constructor for initialization of 'std::exception'

不知道怎么解决。

猜你喜欢

转载自blog.csdn.net/eartha1995/article/details/81032842