Thursday, May 30, 2013

Double Stack template

I decided to show a template form of my previous DoubleStack class so it is not just for ints.

template <typename T>
class DoubleStack
{
    int m_nTopA, m_nTopB, m_nSize;
    int *theStack;

public:
    DoubleStack(int nSize);
    ~DoubleStack(void)
    {
        if (theStack)
            delete theStack;
    }
  
    bool pushA(const T value);
    bool pushB(const T value);
    bool popA(T &value);
    bool popB(T &value);

    bool isFull()
    {
        if (m_nTopA+1 >= m_nTopB)
            return true;
        if (m_nTopB-1 <= m_nTopA)
            return true;
      
        return false;
    }
    bool isAEmpty(){return ((m_nTopA == -1) ? true : false);}
    bool isBEmpty(){return ((m_nTopB == m_nSize) ? true : false);}
};

template <typename T>
DoubleStack<T>::DoubleStack(int nSize)
{
    theStack = NULL;
    m_nSize = nSize;
    m_nTopA = -1;
    m_nTopB = nSize;
    if (m_nSize < 1)
        throw "Stack size must be greater than zero!";
    else
    {
        theStack = new T(m_nSize);
        if (!theStack)
            throw "Error creating the stack!";
    }
}

template<typename T>
bool DoubleStack<T>::pushA(const T value)
{
    if (isFull())
        return false;

    theStack[++m_nTopA] = value;
    return true;
}

template<typename T>
bool DoubleStack<T>::pushB(const T value)
{
    if (isFull())
        return false;

    theStack[--m_nTopB] = value;

    return true;
}

template<typename T>
bool DoubleStack<T>::popA(T &value)
{
    if (isAEmpty())
        return false;

    value = theStack[m_nTopA--];
    return true;
}

template<typename T>
bool DoubleStack<T>::popB(T &value)
{
    if (isBEmpty())
        return false;

    value = theStack[m_nTopB++];
    return true;
}

No comments:

Post a Comment