Saturday 23 November 2013

Tagged under: , , , , , , , ,

How to write a C++ program for the formation of stack or stack formation with pop and push function

#include <iostream>
#include<stdlib.h> //use according to the operating system you use
using namespace::std;
struct p {
struct p *a;
int b;};
p *pop(p *top,p *ptr){

   ptr=top;
   top=ptr->a;
   free(ptr);
   return top;
}
p *push(int ex, p *top){
   p *ptr=NULL;

       ptr=(struct p *)malloc(sizeof(struct p));
       ptr->a=top;
       ptr->b=ex;
       top=ptr;
       return top;}

int main(){
int nik=0;
   p *ptr=NULL,*top=NULL;
   top=(struct p *)malloc(sizeof(struct p));
   top->b=0;
   top->a=NULL;
   int n,ex,t,ni,m=1;
   cout<<"enter the size of the stack"<<endl;
   cin>>n;
   for(int i=0;i<=1;){
   cout<<"press 1 for push, 2 for pop , 3 to empty stack , 0 for exit"<<endl;
   cin>>ni;
   if(ni==1){
       if (m<=n){
   cout<<"enter the number"<<endl;
   cin>>ex;
   top=push(ex,top);
   m++;
   }
   else{
   cout<<"stack is full"<<endl;}
   cout<<endl<<endl<<endl;}
   if(ni==2){
   cout<<"how much you want to pop"<<endl;
   cin>>t;
   for(int i=1;i<=t;i++){
if(top==NULL){
m=0;
break;
}else
   top=pop(top,ptr);
   m--;
   }
if(m!=0){
if(top->b!=0){
   cout<<"now the upper most number in the stack is"<<top->b<<endl;}
   else
   cout<<"stack is empty now"<<endl;
}
else{
cout<<"the stack is empty you can't pop"<<endl;}
cout<<endl<<endl<<endl;
}
if(ni==3){
   for(int i=1;i<=n;i++){

if(top==NULL){
m=0;
break;
}
else
   top=pop(top,ptr);
   m--;
   }
   cout<<"stack is empty now"<<endl<<endl<<endl;
}
if(ni==0){
i=2;}
}
}

Save the code and run it .


Run it in a terminal 
I save the file as a.cpp ,to compile if you are using a gcc compiler then use the command g++ a.cpp,if there is no error then you will get the command prompt next
So then use the command ./a.out ,it will as you to input data and do the job.
Happy coding


0 comments: