Create a stack with pointer - C Data Structure

C examples for Data Structure:Stack

Introduction

A stack is a list that uses first-in, last-out accessing.

The push( ) function places values on the stack, and pop( ) takes them off.

Demo Code

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

#define SIZE 50//from w w  w  . j a va  2 s.  c  om


void push(int i);
int pop(void);

int *tos, *pl, stack[SIZE];

int main(void)
{
   int value;

   tos = stack; /* tos points to the top of stack */

   pl = stack; /* initialize p1 */

   do {
      printf("Enter value: ");
      scanf("%d", &value);

      if (value != 0) push(value);
      else printf("value on top is %d\n", pop());
   } while (value != -1);

   return 0;
}

void push(int i)
{
   pl++;
   if (pl == (tos + SIZE)) {
      printf("Stack Overflow.\n");
      exit(1);
   }
   *pl = i;
}

int pop(void)
{
   if (pl == tos) {
      printf("Stack Underflow. \n");
      exit(1);
   }
   pl--;
   return *(pl + 1);
}

Result


Related Tutorials