Sunday 18 March 2012

Stack implementaion using Array in CPP


Definition : Stack is linear Data Structure, it is a collection of homogeneous data elements where insertion and deletion operation take place at one end only(TOP).

Operation on stack:
  • PUSH   :   insertion into stack
  • POP      :   deletion in stack
  • PEEP    :   display the last ( TOP )  element
Write a program to perform the following operations on a stack using Array (CPP).
    a.    PUSH   
    b.    POP
    c.    ISEMPTY
    d.    ISFULL
    e.    PEEP

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#define N 5

class Stack
{
    int sArr[N];     //stack array
    int top;
public:
    Stack()      //constructor to initialize top
    {
        top=-1;
    }

    void push(int);
    void pop();
    int isEmpty();
    int isFull();
    void peep();
    void display();
};
void Stack :: push(int element)
{
    if(isFull())
    {
        cout<<"\n Stack OverFlow";
    }
    else
    {
        top++;
        sArr[top]=element;
    }
}
void Stack :: pop()
{
    if(isEmpty())
    {
        cout<<"\n Stack UnderFlow";
    }
    else
    {
        cout<<endl<<"Deleted Element is: "<<sArr[top];
        sArr[top]=NULL;
        top--;
    }
}

int Stack :: isEmpty()
{
    if(top<0)
        return 1;
    else
        return 0;
}
int Stack :: isFull()
{
    if(top == N-1)
        return 1;
    else
        return 0;
}

void Stack :: peep()
{
    if(isEmpty())
        cout<<"\n Stack is EMPTY";
    else
        cout<<"\nTOP ELEMENT IS:  "<<sArr[top];
}
void Stack :: display()
{
    cout<<endl<<"\t\t\t";
    for(int i=top ; i >= 0 ; i--)
    {
        cout<<sArr[i]<<endl<<endl<<"\t\t\t";
    }
}


void main()
{
    Stack s;  //object creation
    int ch, data;
    clrscr();
    cout<<"\n\n STACK OPERATIONS";

    while(1)
    {

    cout<<"\n\n1. PUSH";
    cout<<"\n2. POP";
    cout<<"\n3. PEEP";
    cout<<"\n4. EXIT";
    cout<<"\nEnter Choice: ";
    cin>>ch;
    clrscr();
        cout<<"\n\n STACK OPERATIONS\n\n";

        switch(ch)
        {
        case 1:
            cout<<"\n Enter Value: ";
            cin>>data;

            s.push(data);
            s.display();
            break;
        case 2: s.pop();
            s.display();
            break;
        case 3: s.peep();
            break;
        case 4: exit(0);
            break;
        }
    }
getch();
}

Kindly Bookmark and Share it:

0 comments :

Post a Comment

Any Query ? any suggestion ? comment here

 

Recent Post

Recent Comments

© 2010 IamLearningHere Template by MBT