Example C Code: Stacks Using Arrays

#include < stdlib.h >
#include < stdio.h >

typedef struct { int *stk ; int maxelem; int top; } STACK;

STACK *init(int n)
{
   STACK *s = (STACK *)malloc(sizeof(STACK));
   s->top = 0;
   s->maxelem = n;
   s->stk = (int *)malloc(sizeof(int)*n);
   return s;
}

void push(STACK *s, int data)
{
   if (s == NULL) return;
   if (s->top == s->maxelem) return;
   s->stk[s->top++] = data;
}

int pop(STACK *s)
{
   if (s == NULL) return -1;
   if (s->top == 0) return -1;
   s->top--;
   return  s->stk[s->top];
}

void deleteNode(STACK *s, int data)
{
   if (s == NULL) return;
   if (s->stk[s->top-1] == data) { s->top--; return; }
   for (int i=s->top-1 ; i >= 0 ; i--)
   {
      if (s->stk[i] == data)
      {
         for ( ; i < s->top ; i++) s->stk[i] = s->stk[i+1];
         s->top--;
         return;
      }
   }
}

void display(STACK *s)
{
   for (int t=0 ; t < s->top ; t++) printf(" %d", s->stk[t]);
   printf("\n");
}

void main()
{
   STACK *s = NULL;
   int d;

   s=init(100);
   push(s, 1);
   display(s);
   push(s, 2);
   display(s);
   push(s, 3);
   display(s);
   pop(s);
   display(s);
   push(s, 10);
   display(s);
   push(s, 11);
   display(s);
   deleteNode(s,2);
   display(s);
   deleteNode(s,1);
   display(s);
   deleteNode(s,11);
   display(s);
}