Software & Finance





Turbo C - Sample Stack Implementation





I have given here the source code in Turbo C for Stack (Last In First Out). 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 <stdio.h>

#include <alloc.h>

#include <stdlib.h>

#include <string.h>

 

typedef struct _MyStack

{

    int *m_data;

    int m_numElements;

} MyStack;

 

int push(MyStack *s, int data)

{

        if(s->m_data == NULL) // root node

        {

            s->m_numElements = 1;

            s->m_data = (int*) malloc(sizeof(int));

        }

        else

        {

            s->m_numElements++;

            s->m_data = realloc(s->m_data, s->m_numElements * sizeof(int));

            memmove(&s->m_data[1], s->m_data, (s->m_numElements - 1) * sizeof(int));

        }

 

        s->m_data[0] = data;

        return 1;

}

 

int pop(MyStack *s)

{

        if(s->m_data == NULL) // root node

        {

                s->m_numElements = 0;

                return 0;

        }

        else

        {

            if(s->m_numElements == 1)

            {

                // last item

                s->m_numElements = 0;

                free(s->m_data);

                s->m_data = NULL;

            }

            else

            {

                s->m_numElements--;

                memmove(s->m_data, &s->m_data[1], s->m_numElements * sizeof(int));

                s->m_data = (int*) realloc(s->m_data, s->m_numElements * sizeof(int));

            }

        }

        return 1;

}

 

int top(MyStack *s)

{

        if(s->m_numElements > 0)

            return s->m_data[0];

        return 0;

}

 

int size(MyStack *s)

{

        return s->m_numElements;

}

 

int main()

{

    MyStack *s1 = malloc(sizeof(MyStack));

    int sz, i;

 

    push(s1, 10);

    push(s1, 20);

    push(s1, 30);

    push(s1, 40);

    pop(s1);

    push(s1, 40);

    push(s1, 50);

 

    sz = size(s1);

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

    {

        printf("%d\n", top(s1));

        pop(s1);

    }

 

    return 0;

}

 
Click here to download Turbo C Source Code and Executable

Output


50

40
30
20
10

Press any key to continue . . .