Monday, 6 February 2012

Stack Implementaion in C++

A stack is a last in, first out (LIFO) abstract data type and linear data structure. A stack can have any abstract data type as an element, but is characterized by only three fundamental operations: push, pop and stack top. The array implementation aims to create an array where the first element (usually at the zero-offset) is the bottom.
In this source code I have implemented Push and Pop function through C++  by using classes, It is easy to understand and implement, each line code have its description along it. 
***************************************************************
 Author: Sunil Kumar
 Web: www.techdoon.com
 Description: C++ Program implement a stack using an array
***************************************************************/
# include<iostream>
# include<cstdlib>
# define SIZE 20
using namespace std;
class stack
{
      private:
              int a[SIZE];
              int top; // Top of Stack
      public:
            stack();
           void push();
           int pop();
           int isEmpty();
           int isFull();
};
stack::stack()
{
              top=0;
}
int stack::isEmpty() //check stack for underflow
{
 return(top==0?1:0);   
}
int stack::isFull() //check stack overflow
{
    return(top==SIZE?1:0); 
}
void stack::push()//insert item
{
    int item;
    if(!isFull()){
                  cout<<"\nITEM:"; cin>>item;
                  a[top]=item;
                  top++;
         }
    else{
         cout<<"Stack OverFlow Error.";
         }
    }
int stack::pop() //pop item
{
    if(!isEmpty()){
                   return(a[--top]);
                   }
    else{
         cout<<"Stack Underflow Error.";
         }
}
int main()
{
    stack s;
    int n,i=1;
    cout<<"No. Of item you want to push:\n";
    cin>>n;
   while(i<=n)
    {
    s.push();
    i++;
    }
    cout<<s.pop()<<endl;
    system("PAUSE"); //pause output screen
    return 0;
}

Related Posts:



0 comments:

Post a Comment