Sunday 25 September 2011

Stack push operations

PUSH OPERATIONS

 (i) top =-1 when the stack is empty
 (ii) top =0 after inserting data A on to the stack
 (iii) top =1 after inserting data B onto the stack
 (iv) top =2 after inserting data C on to the stack
 
PUSH ALGORITHM FOR STACKS
1. If top = max_size // if the stack is full we cannot push an element onto the stack.
2. then Print "Stack Overflow or Stack is full ";
3. Endif
4. Else
5. top = top + 1 //Increase top by 1
6. Set stack[top] = x //Insert item onto the top of the stack, here x is actual parameter
7. End

//stack program
template<class T>
class stack
{
 private:
  T *s;
  int top,size;
 public:
  void push(T x);

  stack(int k=40);

  int isfull();
  int isempty();
  void display();

 };
 template<class T>
stack<T>::stack(int k)
{
 top=-1;
 size=k;
 s=new T[size];
}
//isempty()
template<class T>
int stack<T>::isempty()
{
 return(top==-1);
}
//isfully

int stack<T>::isfull()
{
 return(top==size-1);
}
template<class T>
void stack<T>::push(T x)
{
 if(isfull())
 {
  cout<<"stack is full,Insertion is not possible\n";
 }
 else
 {
  top++;
  s[top]=x;
 }
}

template<class T>
void stack<T>::display()
{
 if(isempty())
  cout<<"stack is empty\n";
 else
 {
  cout<<"stack is as follows\n";
  for(int i=top;i>=0;i--)
   cout<<s[i]<<"\n";
 }
}
void main()
{
 int ch,k,x;
 cout<<"enter size of the stack\n";
  cin>>k;
        stack<int> a(k);
        cout<<"enter value to be inseted\n";
        cin>>x;
        a.push(x);
        a.display();
     getch();
 }


Basic stack operation

No comments:

Post a Comment