Sunday, 2 September 2012

Stack implementation using Linked lists


#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

struct node
{
    int x;
    struct node *next;
};

class stack
{
private:
    struct node *top;
public:
    stack()
    {
    top=NULL;
    cout<<"stack is created"<<endl;
    }
    void menu();
    void push();
    void pop();
    void display();
};

void stack::menu()
{
    int ch;
    do
    {
    cout<<endl;
    cout<<"STACK MENU"<<endl
        <<"1.push"<<endl
        <<"2.pop"<<endl
        <<"3.Display"<<endl
        <<"4.Exit"<<endl;
    cout<<"Enter your choice : ";
    cin>>ch;

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

    case 2: pop();
        break;

    case 3:    display();
        break;

    case 4: exit(0);
        break;

    default:
        cout<<"Sorry! invalid choice"<<endl;

    }
    }while(ch!=4);
}

void stack::push()
{
    node *temp;
    int a;
    cout<<"Enter data : ";
    cin>>a;
    temp=new node;
    temp->x=a;
    temp->next=top;
    top=temp;
}

void stack::pop()
{
    node *temp;
    if(top==NULL)
      cout<<"stack is empty"<<endl;
     else
      {
       temp=top;
       cout<<"poped element is : "<<temp->x;
       top=top->next;
       delete temp;
      }
}

void stack::display()
{
    node *ptr;
    if(top==NULL)
       cout<<"stack is empty"<<endl;
     else
      {
       cout<<"Stack elements are : ";
       for(ptr=top;ptr!=NULL;ptr=ptr->next)
           cout<<ptr->x<<" ";
       cout<<endl;
      }
}

void main()
{
   clrscr();
   stack s;
   s.menu();
   getch();
}

No comments:

Post a Comment