21. Stack containing min function

  Topic : Define the data structure of the stack, please implement a min function in this type that can get the smallest element of the stack. In this stack, the time complexity of calling min, push, and pop are all 0(1).

 Idea : Build a data stack and an auxiliary stack. The data stack is normally pushed with data, and the auxiliary stack is pushed with the minimum data. For example, the elements to be added to the stack now are: 4, 3, 6, and 2. The actions of pushing into the stack are as follows:
  1. Because 4 is the first element, it is pushed into the data stack and the auxiliary stack at the same time.
  2. Then 3, because 3 is smaller than 4, it is also pushed into the data stack and the auxiliary stack at the same time.
  3. Next is 6, because 6 is larger than the smallest element 3 in the auxiliary stack, so it is not pushed into the auxiliary stack, but another 3 needs to be pushed into the auxiliary stack, so as to ensure the minimum value before the data stack 3 is not popped Keep 3.
  4. Because 2 is smaller than 3, it is also pushed into the data stack and the auxiliary stack at the same time.

  Test case : normal test.

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

template<typename T> class StackWithMin
{

public:
    StackWithMin(){}
    virtual ~StackWithMin(){}
    void push(const T& value);
    void pop();
    const T& min() const;

private:
    stack<T>    m_data;
    stack<T>    m_min;
};

template <typename T> void StackWithMin<T>::push(const T& value)
{
    m_data.push(value);

    if (m_min.size() == 0 || value < m_min.top())
    {
        m_min.push(value);
    }
    else
    {
        m_min.push(m_min.top());
    }
}

template <typename T> void StackWithMin<T>::pop()
{
    if (m_data.size() > 0 && m_min.size() > 0)
    {
        m_data.pop();
        m_min.pop();
    }

}

template <typename T> const T& StackWithMin<T>::min() const
{
    if (m_data.size() > 0 && m_min.size() > 0)
    {
        return m_min.top();
    }
}

void Test(const StackWithMin<int>& stack, int expected)
{
    if (stack.min() == expected)
    {
        cout << "pass!" << endl;
    }
    else
    {
        cout << "failed!" << endl;
    }
}

int main()
{
    StackWithMin<int> stack;

    stack.push(3);
    Test(stack, 3);

    stack.push(4);
    Test(stack, 3);

    stack.push(2);
    Test(stack, 2);

    stack.push(3);
    Test(stack, 2);

    stack.pop();
    Test(stack, 2);

    stack.pop();
    Test(stack, 3);

    stack.pop();
    Test(stack, 3);

    stack.push(0);
    Test(stack, 0);

    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325145968&siteId=291194637