剑指offer第五题 用两个栈实现队列

题目描述

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

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

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

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

但这里很奇怪,正常pop函数会返回值的?但是我直接用temp=stack.pop()的时候显示void与int类型不符合

而且这里写的有点复杂了,不需要将stack2中的再返回stack1中去了

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

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

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

这样写的话要对stack2进行判断,如果stack2不为空的时候,说明上次从stack1中Push进来的值还没pop完,就直接在stack2中进行pop就可以了,如果为空再去看stack1中是不是还有值可以push进stack2中

猜你喜欢

转载自blog.csdn.net/qq_38284204/article/details/88355579