Example C Code: Stacks Using Linked Lists

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

typedef struct node { int data; struct node *next; } NODE;

NODE *push(NODE *l, int data)
{
   NODE *tmp = (NODE *)malloc(sizeof(NODE));
   tmp->data = data;
   tmp->next = l;
   return tmp;
}

NODE *pop(NODE *l, int *data)
{
   NODE *tmp;
   if (l==NULL) return NULL;
   *data = l->data;
   if (l->next==NULL) return NULL;
   tmp=l->next;
   free (l);
   return tmp;
}

NODE *deleteNode(NODE *l, int data)
{
   NODE *tmp, *tmp1;
   if (l == NULL) return NULL;
   if (l->data==data)
   {
      tmp=l->next;
      free(l);
      return tmp;
   }
   tmp=l;
   tmp1=l->next;
   while (tmp1 != NULL)
   {
      if (tmp1->data==data)
      {
         tmp->next=tmp1->next;
         free(tmp1);
         return l;
      }
      tmp=tmp1;
      tmp1=tmp1->next;
   }
   return l;
}

void display(NODE *l)
{
   NODE *tmp;
   for (tmp=l ; tmp != NULL; tmp=tmp->next) printf(" %d",tmp->data);
}

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

   s=push(s, 1);
   s=push(s, 2);
   s=push(s, 3);
   display(s);
   s=deleteNode(s,2);
   printf("\n");
   display(s);
}