【數據結構】 兩個棧實現一個隊列【面試】

棧結構:先進後出,後進先出,只容許在棧尾操做。ios

隊列:先進先出,在隊尾入隊,在隊頭出隊。ide

要想用兩個棧實現一個隊列,就須要使用一個至關於中間量的結構進行隊列的入隊和出隊操做。函數


用圖形象化爲:spa

wKiom1cTKdyAGgZmAAAdDuQIW7Q496.png

這樣問題就從圖中得出了思路:3d

入隊操做:把入隊元素一一存入一個棧結構中便可。blog

出隊操做:出隊時,先判斷另外一個棧結構中是否有元素,如有先將元素出棧Pop();若爲空,則把棧S1中的元素所有倒入Push()棧S2中,而後讓S2棧頂元素出棧Pop(),此時的元素序列和棧S1中恰好相反,即達到出隊效果。隊列


那麼,用代碼實現也變得簡單:get

#include <iostream>
#include <stack>
using namespace std;

class Queue
{
public:
    void Push_Queue(int val)
    {
        s1.push(val);   // 實現了入隊尾入隊操做
        cout <<s1.top() << " ";
    }

    void Pop_Queue()
    {
        if (s2.empty())
        {
            while (s1.top())
            {
                s2.push(s1.top()--);
            }
             s2.pop();  // 實現了隊頭出隊操做
        }
        else
        {
            s2.pop();
        }
    }

    void Show()
    {
        cout << endl;
        // 由於使用的是系統庫stack,其pop函數返回值爲void,因此不能打印出來,咱們只打印pop後的隊頭元素進行驗證
        cout << s2.top() << endl; 
    }

private:
    stack<int> s1;
    stack<int> s2;

};

int main()
{
    Queue q;  // ??構造函數的參數
    q.Push_Queue(1);
    q.Push_Queue(2);
    q.Push_Queue(3);
    q.Push_Queue(4);
    q.Push_Queue(5);

    q.Pop_Queue();

    q.Show(); // 打印pop後的對頭元素

    system("pause");
    return 0;
}

若有紕漏,歡迎指正。
it

相關文章
相關標籤/搜索