Saturday, 13 April 2013

C++ program for stack using linked list

/*Program for Stack Using Linked-List
     By sanjay kumar singh,ggsestc*/



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

void push();
void pop();
void display();

struct node
{
int data;
      node *next;
};
node *top=NULL;

void main()

{
         int n;
         do
         {
         cout<<"enter the choice from the following \n";
         cout<<"1...push\n2...push\n3...peep\n4...display\n";
         cin>>n;
         switch(n)
         {
          case 1:cout<<"...push operation...\n";
                      push();
                      break;
               case 2:cout<<"...pop operation...\n";
                      pop();
                      break;
               case 4:cout<<"...display operation...\n";
               display();
                      break;
          }
          }while(n<5);
   getch();
}

void push()
{
      int n;
      node *temp;
      cout<<"enter the element u want to insert : ";
      cin>>n;
      temp=(node*)malloc(sizeof(node));
      temp->data=n;
      temp->next=top;
      top=temp;
}
void pop()
{
      int n;
      node *temp;
      if(top==NULL)
      cout<<"stack underflow";
      else
      {
      temp=top;
            top=top->next;
            temp->next=NULL;
            cout<<"deleted element is "<<temp->data;
            free(temp);
      }
}

void display()
{
      node *show;
      if(top==NULL)
      cout<<"stack is empty";
      else
      {
          show=top;
            while(show!=NULL)
            {
              cout<<show->data<<"\t";
                  show=show->next;
             }
       }
}

No comments:

Post a Comment