NC76 用两个栈实现队列

Posted Jqivin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NC76 用两个栈实现队列相关的知识,希望对你有一定的参考价值。

题目描述

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

解题思路

首先,有两个栈,stack1,stack2,。我们用stack1来执行push操作,直接stack1.push(n)就可以。在stack2中执行pop操作,需要分两种情况,(1)stack2为空,这时候,要把Stack1中的元素挪到stack2中,然后在进行pop。(2)不为空,直接pop就可以了。

代码展示

class Solution
{
public:
    void Swap()
    {
     //for (int i = 0; i < stack1.size(); i++)   //错误stack.size()每次都在变化,第一次做错的原因
        while(!stack1.empty())
            {
                stack2.push(stack1.top());
                stack1.pop();
            }
    }
    void push(int node) {
        
        stack1.push(node);
    }

    int pop() {
        if(stack2.empty())
        {
            Swap();
        }
        int res = stack2.top();
        stack2.pop();
        return res;
    }

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

以上是关于NC76 用两个栈实现队列的主要内容,如果未能解决你的问题,请参考以下文章