用两个队列实现一个栈

队列是先进先出,而栈是先进后出;

考虑到我们取栈顶元素的便利性,我们在实现时使得栈顶等于队列头;

由于栈的pop弹出栈顶元素,而队列的pop也是弹出栈顶元素,所以我们需要特别处理的是插入操作。

由于往栈中添加元素相当于往队列头添加元素,因此我们需要在两个队列中进行元素的转移,比较简单的实现是:

1.q1和q2在任一时刻至少有一个为空,即如果有元素,所以元素只在同一个队列中。 
2.当有元素需要插入时,将插入的元素插入到空的队列中,并将另一非空队列的元素转移到该队列中,于是插入的元素添加到了队列头中。

(当然,你可以换一种思路,把队列尾与栈顶对应起来,这样子需要特别处理的是pop操作以及top操作,相比起来,本文的做法更加简便,因为只需要对插入操作特别处理)

具体C++代码实现如下:

class Stack {public:    // Push element x onto stack.
    void push(int x) {        if (!q1.empty())
        {
            q2.push(x);            while (!q1.empty())
            {
                q2.push(q1.front());
                q1.pop();
            }
        }        else
        {
            q1.push(x);            while (!q2.empty())
            {
                q1.push(q2.front());
                q2.pop();
            }
        }
    }    // Removes the element on top of the stack.
    void pop() {        if (q1.empty()&&q2.empty())            throw new exception("stack is empty");        else if (!q1.empty()) q1.pop();        else q2.pop();
    }    // Get the top element.
    int top() {        if (!q1.empty()) return q1.front();        else return q2.front();
    }    // Return whether the stack is empty.
    bool empty() {        return (q1.empty()&&q2.empty());
    }private:    queue<int> q1, q2;
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章