Free Hosting

C++ Stack Program using array

C:\Users\Jatinder\Desktop\StackWithArray_cpp.html <!-- Exported by C-Free C/C++ IDE
#include<iostream.h>
#include<conio.h>
#include<string.h>
class StackFullException:public std::exception
{
 public:
 StackFullException()
 {
  
 }
 virtual const char* what() const throw()
 {
  return ("Stack is Full ");
 }
};
class StackPosException:public std::exception
{
 public:
 StackPosException()
 {
 }
 virtual const char* what() const throw()
 {
  return ("This Location does not exist in stack");
 }
};
class StackEmptyException:public std::exception
{
 public:
 StackEmptyException()
 {
 }
 virtual const char* what() const throw()
 {
  return ("Stack is Empty");
 }
};
template <class T>
class StackWithArray
{
 private:
   T S[10];
   int TOS;
   int n;
   bool isstackfull()
   {
    return(TOS==n);
   }
   bool isstackempty()
   {
    return(TOS==-1);
   }
   bool isvalidposition(int pos)
   {
    return(pos<=n);
   }
 public:
   StackWithArray()
   {
        n=0;
     TOS=-1; 
   }
   StackWithArray(int nn)
   {
     n=nn;
     TOS=-1; 
   }
   void push(T element)
   {
     if(isstackfull())
     {
      throw StackFullException();
      }
      else
      {
        TOS++;
        S[TOS]=element;
      }
    }
    T pop()
    {
     if(isstackempty())
     {
      throw StackEmptyException();
     }
     else
     {
      return(S[TOS--]);
     }
    }
    T peep(int pos)
    {
     if(pos>TOS)
     {
      throw ;
     } 
     else
      return(S[pos-1]);
    }
        friend ostream& operator<<(ostream &o,StackWithArray<T> tem)
    {
     for(int i=0;i<=tem.TOS;i++)
     {
      o<<tem.S[i]<<endl;
     }
    }
};
int main()
{
 
 StackWithArray<int> stack(2);
 try
 { 
 stack.push(13);
 stack.push(14);
 stack.push(100);
 //stack.push(14);
 cout<<stack.pop()<<endl;
 cout<<stack.pop()<<endl;
 cout<<stack.pop()<<endl;
 //cout<<stack.pop()<<endl;
 //int numer=stack.peep(5);*/
 }
 catch(StackFullException e1)
 {
  cout<<e1.what();
 }
 catch(StackEmptyException e2)
 {
  cout<<e2.what();
 }
 catch(StackPosException e3)
 {
  cout<<e3.what();
 }
 cout<<stack;
 getch();
 return 0;
}

-->

0 comments:

Blogger Template by Clairvo