筆試題:由兩個棧構造min棧

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

template<typename T>
class Min
{
public:
    void PUSH(T val)
    {
        T temp = val;
        st1.push(val);
        if (st2.empty() == true)
        {
            st2.push(temp);
            st1.push(temp);
        }
        else
        {
            st2.pop();
            while (st1.empty() == false)
            {
                if (st1.top() < temp)
                {
                    temp = st1.top();
                }
                st2.push(st1.top());
                st1.pop();
            }
        }
        while (st2.empty() == false)
        {
            st1.push(st2.top());
            st2.pop();
        }
        st2.push(temp);
    }
    void POP()
    {
        st2.pop();
        if (st1.empty() == true)return;
        st1.pop();
        int temp = st1.top();
        while (st1.empty() == false)
        {
            if (temp > st1.top())
            {
                temp = st1.top();
            }
            st2.push(st1.top());
            st1.pop();
        }
        while (st2.empty() == false)
        {
            st1.push(st2.top());
            st2.pop();
        }
        st2.push(temp);
    }
    T min()
    {
        if (st2.empty()==false)
        return st2.top();
    }
private:
    stack<T> st1;
    stack<T> st2;
};
int main()
{
    Min<int> m;
    m.PUSH(1);
    m.PUSH(2);
    m.PUSH(3);
    m.PUSH(4);
    m.PUSH(5);
    m.PUSH(6);
    m.PUSH(7);
    m.PUSH(0);
    cout << m.min() << endl;
    m.POP();
    cout << m.min() << endl;


    m.PUSH(1);

    m.PUSH(1);
    m.PUSH(1);
    return 0;
}
發佈了291 篇原創文章 · 獲贊 25 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章