Friday, June 14, 2013

STACK IMPLEMENTATION

STACK IMPLEMENTATION (C++ CODE):

//stack


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


class stack_sll
 {
    private:
    struct stack
      {
 int data;
 struct stack *next;
      }*top;
    public:
   stack_sll()
      {
 top =NULL;
      }
   void push(int x);
   int pop();
   void display();
 };

void main()
 {
      stack_sll ob1;

      char choice;
      int ch,val;
      clrscr();
      do
      {

cout<<"\n MENU: \n 1.push.\n 2.pop.\n";
cout<<"\n Enter your choice:";
cin>>ch;

switch(ch)
{
case 1:
cout<<"\n Enter the data :" ;
cin>>val;
ob1.push(val);
ob1.display();
break;

case 2:
val=ob1.pop();
ob1.display();
if(val == 0)
     cout<<"\n Stack Is Empty...";
else
     cout<<"\n Element poped from stack is :"<<val;

break;

}
cout<<"\n Do you want to continue(y/n)";
cin>>choice;
    }while(choice=='y' || choice =='Y');
}

void stack_sll :: push(int x)
  {
    stack *node;
    node =new stack;
    node->data = x;
    node->next = NULL;
    if(node == NULL)
   cout<<"\n Stack Is Full";

    if(top == NULL)
{
   top = node;
}
    else
{
   node->next = top;
   top = node;
}
  }

int stack_sll :: pop()
  {
      stack *temp;
      int val;
      if(top == NULL)
      return 0;
      else
   {
temp = top;
val = temp->data;
top=top->next;
delete(temp);
   }
       return(val);
  }

void stack_sll::display()
  {
      stack *temp = top;
      cout<<"\n Data on stack is:";
      while(temp != NULL)
  {
      cout<<" "<<temp->data;
      temp = temp->next;
  }
  }


No comments:

Post a Comment

Thanks for your valuable comment