美文网首页算法练习
栈实现队列(双栈,临时栈)

栈实现队列(双栈,临时栈)

作者: 倚剑赏雪 | 来源:发表于2020-02-18 21:06 被阅读0次

    //利用双栈法

    Stack<int> inputStack = new Stack<int>();
    Stack<int> outStack = new Stack<int>();
    void Push(int x)
    {
        inputStack.Push(x);
    }
    int Pop()
    {
        Adjust();
        return outStack.Pop();
    }
    int Peek()
    {
        Adjust();
        return outStack.Peek();
    }
    void Adjust()
    {    if (outStack.Count>0) return;
        while (inputStack.Count>0)
    {
            outStack.Push(inputStack.Pop());
    }
    }
    

    利用临时栈

      Stack<int> resStack = new Stack<int>();
        void Push1(int x)
        {
            Stack<int> tempStack = new Stack<int>();
            while (resStack.Count>0)
            {
                tempStack.Push(resStack.Pop());
            }
            tempStack.Push(x);
            while (tempStack.Count>0)
            {
                resStack.Push(tempStack.Pop());
            }
        }
    
    

    相关文章

      网友评论

        本文标题:栈实现队列(双栈,临时栈)

        本文链接:https://www.haomeiwen.com/subject/iaunfhtx.html