Stack Example in C++


Prev Tutorial Next Tutorial

Example of Stack in C++

Program of stack is very simple when you insert any item in stack top will be increased by 1 and when you pop any item from stack top will be decreased by 1. Both insertion and deletion operation in stack perform from top of stack.

Stack Example in C++

	
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

#define size 5

void pop();
void push();
void display();

 struct stack
  {
   int item;
   int stack[size];
  }s;

  int top=-1;

  void push()
  {
  if(top==size-1)
  {
  cout<<"\n stack is full";
  }
  else
  {
  top=top+1;
  cout<<"\n\n Enter element in stack: ";
  cin>>s.item;
  s.stack[top]=s.item;
  }
  }

  void pop()
  {
  if(top==0)
  {
  cout<<"\nStack is empty: ";
  }
  else
  {
  s.item=s.stack[top];
  top=top-1;
  cout<<"deleted data is: "cout<<s.item;
  }
  }

  void display()
  {
   int i;
   if(top==0)
   {
   cout<<"\n Stack is empty: ";
   }
   else
   {
    for(i=top;i>0;i--)
    {
    cout<<"\n s.stack[i]";
    }
   }
  }

  void main()
  {
   char ch,c;

   do
   {
   u:
   clrscr();
   cout<<"\n\n1: push";
   cout<<"\n2: pop";
   cout<<"\n3: display";
   cout<<"\n4: exit";
   cout<<"\nEnter your choice: ";
   cin>>c;
   switch(ch)
   {
    case 1:
	 up:
	 push();
	 break;
    case 2:
	 pop();
	 break;
    case 3:
	 display();
	 break;
    case 4:
	 exit(0);
	 break;
    default:
	 cout<<"\nwrong choice";
   }
   cout<<"\n\n Pushed an element (Y/N)";
   c=getch();
   if(c=='y'||c=='Y')
   {
   goto up;
   }
   else
   {
   goto u;
   }
   }
   while(ch!=5);
  }
stack example in c++
Prev Tutorial Next Tutorial

Advertisements




Download Projects