What is Stack

A stack is a linear data structure which allows any kind of operations on only top of the stack. Stack follows particular order only i.e LIFO(Last In First Out) or FILO(First In Last Out).

How to understand a stack practically?

There are many real-life examples of the stack. Consider the simple example of plates stacked over one another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottom-most position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO/FILO order.

Stack implementation using an array

#include <stdio.h>

#define MAX_SIZE 5
int top=-1;
int STACK[MAX_SIZE];
void push()
{
  int data;
  if(top==MAX_SIZE-1)
  {
    printf("\nSTACK IS FULL");
    return;
  }
  printf("\nEnter data: ");
  scanf("%d",&data);
  STACK[++top]=data;
  return;
}
void pop()
{
  if(top==-1)
  {
   printf("\nSTACK IS EMPTY");
   getch();
   return;
  }
  printf("\ndeleted data:%d",STACK[top]);
  --top;
  return;
}
void peek()
{
  int i;
  if(top==-1)
  {
   printf("\nSTACK IS EMPTY");
   return;
  }
  printf("\nSTACK DATA: ");
  for(i=top; i>=0; i--)
  printf("%d ",STACK[i]);
  return;
}
int main()
{
  int option;
  while(1)
  {
   clrscr();
   printf("\n1.FOR PUSH : ");
   printf("\n2.FOR POP  : ");
   printf("\n3.FOR PEEK : ");
   printf("\n4.FOR EXIT : ");
   scanf("%d",&option);
   switch(option)
   {
    case 1: push();
          break;
    case 2: pop();
          break;
    case 3: peek();
          break;
    case 4: return 0;

    default: printf("\nInvalid Option: ");
   }
     }
     return 0;
}






Leave a Reply

Your email address will not be published. Required fields are marked *