Software & Finance





Visual C++ - Sample Stack With Template





I have given here the source code in Visual C++ for Stack (Last In First Out). I have used templates. For dynamic memory allocation, I have used malloc, realloc and free functions.

 

The other related links are,

Visual C++ - Sample Stack With Template

Turbo C++ - Sample Stack With Template

Turbo C - Sample Stack Implementation


Source Code


#include <iostream>

#include <stdio.h>

#include <tchar.h>

 

 

template<class T>

class MyStack

{

    T *m_data;

    int m_numElements;

 

public:

    MyStack() : m_data(NULL), m_numElements(0) { }

    ~MyStack()

    {

        free(m_data);

        m_data = NULL;

        m_numElements = 0;

    }

 

    bool empty()

    {

        free(m_data);

        m_data = NULL;

        m_numElements = 0;

        return true;

    }

 

    bool push(T data)

    {

        if(m_data == NULL) // root node

        {

            m_numElements = 1;

            m_data = (T*) malloc(sizeof(T));

        }

        else

        {

            m_numElements++;

            m_data = (T*) realloc(m_data, m_numElements * sizeof(T));

            memmove(&m_data[1], m_data, (m_numElements - 1) * sizeof(T));

        }

 

        m_data[0] = data;

        return true;

    }

 

    bool pop()

    {

        if(m_data == NULL) // root node

        {

            return false;

            m_numElements = 0;

        }

        else

        {

            if(m_numElements == 1)

            {

                // last item

                m_numElements = 0;

                free(m_data);

                m_data = NULL;

            }

            else

            {

                m_numElements--;

                memmove(m_data, &m_data[1], m_numElements * sizeof(T));

                m_data = (T*) realloc(m_data, m_numElements * sizeof(T));

            }

        }

        return true;

    }

 

    T top()

    {

        if(m_numElements > 0)

            return m_data[0];

    }

 

    int size()

    {

        return m_numElements;

    }

 

};

 

 

int _tmain(int argc, _TCHAR* argv[])

{

    MyStack<int> s1;

 

    s1.push(10);

    s1.push(20);

    s1.push(30);

    s1.push(40);

    s1.pop();

    s1.push(40);

    s1.push(50);

 

    int sz = s1.size();

    for(int i = 0; i < sz; i++)

    {

        std::cout << s1.top() << "\n";

        s1.pop();

    }

 

      return 0;

}

 

  
Click here to download Visual C++ Source Code and Executable

Output


50

40

30

20

10