Thursday, January 15, 2015

How to implement Stack by Array in C++?

#include<iostream>
#include<conio.h>
#include<stdio.h>
//#include<stack>
using namespace std;


#define max 5
int Stack_Array[max];
int top=-1;
void push();
void pop();
void display();

main()
{
int choice;
while(1)
{
cout<<"1: Push"<<endl;
cout<<"2: Pop"<<endl;
cout<<"3: Display"<<endl;
cout<<"4:Quit"<<endl;
cin>>choice;

switch(choice)
{
case 1:
push();
break;

case 2:
pop();
break;

case 3:
display();
break;

case 4:
return 0;;

default:
cout<<"Wrong Choice"<<endl;

}  //end of switch
}  //end of while
}   //end of main

void push()
{
int pushed_item;
if(top==(max-1))
    cout<<"Stack_Array Overflow"<<endl;
else
{
    cout<<"Enter the item to be pushed in Stack_Array:"<<endl;
    cin>>pushed_item;
    top=top+1;
    Stack_Array[top]=pushed_item;

}
}


void pop()
{
if(top==-1)
    cout<<"Stack_Array Underflow"<<endl;
else
{
    cout<<"Poped element is:"<<Stack_Array[top]<<endl;
    top=top-1;
}
}


void display()
{
int i;
if(top==-1)
    cout<<"Stack_Array Empty"<<endl;
else
{
    cout<<"Stack_Array element:"<<endl;
    for(i=top;i>=0;i--)
    cout<<Stack_Array[i]<<endl;
}
}

No comments:

Post a Comment