每天幾道面(筆)試題

1.兩個棧實現一個隊列、兩個隊列實現一個棧

//兩個隊列實現一個隊列
class Solution
{
public:
    void push(int node) 
    {
        stack1.push(node);
    }

    int pop() 
    {
        if( stack2.size() <= 0)
        {
            while( stack1.size() > 0)
            {
                int data = stack1.top();
                stack1.pop();
                stack2.push(data);
            }
        }
        int val = stack2.top();
        stack2.pop();
        return val;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
//兩個隊列實現一個棧
class Stack
{
public:
    void push(int data)
    {
        queue1.push(data);
    }
    void pop()
    {
        while( !queue1.empty())
        {
            if( queue2.empty() )
            {
                while( queue1.size() != 1)
                {
                    int data = queue1.front();
                    queue1.pop();
                    queue2.push(data);
                }
                int data = queue1.front();
                queue1.pop();
                cout<<data<<" ";
            }
        }

    }
private:
    queue<int> queue1;
    queue<int> queue2;
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章