1. 程式人生 > 實用技巧 >用佇列實現棧

用佇列實現棧

使用佇列實現棧的下列操作:

push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否為空

思路

棧是一種 後進先出(last in - first out, LIFO)的資料結構,棧內元素從頂端壓入(push),從頂端彈出(pop)。一般我們用陣列或者連結串列來實現棧,但是這篇文章會來介紹如何用佇列來實現棧。佇列是一種與棧相反的 先進先出(first in - first out, FIFO)的資料結構,佇列中元素只能從 後端(rear)入隊(push),然後從 前端(front)端出隊(pop)。為了滿足棧的特性,我們需要維護兩個佇列 q1 和 q2。同時,我們用一個額外的變數來儲存棧頂元素。

演算法

壓入(push)

新元素永遠從 q1 的後端入隊,同時 q1 的後端也是棧的 棧頂(top)元素。

class MyStack {
public:
    //單鏈表實現
    /** Initialize your data structure here. */
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        int size = q.size();
        q.push(x);
        int tmp;
        
for(int i = 0; i < size; i++){ q.push(q.front()); q.pop(); } } /** Removes the element on top of the stack and returns that element. */ int pop() { int tmp = q.front(); q.pop(); return tmp; } /** Get the top element.
*/ int top() { return q.front(); } /** Returns whether the stack is empty. */ bool empty() { return q.empty(); } private: queue<int> q; };
class MyStack {
//雙佇列實現棧
public:
    /** Initialize your data structure here. */
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        pushQueue.push(x);
        topValue = x;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        while(pushQueue.size()>1){
            topValue = pushQueue.front();
            popQueue.push(topValue);
            pushQueue.pop();
        }
        int result = pushQueue.front();
        pushQueue.pop();
        queue<int> tmp = pushQueue;
        pushQueue = popQueue;
        popQueue = tmp;
        return result;
    }
    
    /** Get the top element. */
    int top() {
        return topValue;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return pushQueue.empty();
    }

private:
    queue<int> pushQueue;
    queue<int> popQueue;
    int topValue;
};