C++ Programming Blog

 
 
 

Image

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


 main()
    {
       clrscr();

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

       node *start;
       node *top;
       node *entry;
       node *last;
       node *last2;
       node *print;

       int num;
       int l;

       char ch;

       start=NULL;
       top=NULL;

       do
      {
         clrscr();

         cout<<\"Enter \\n\\t \'p\' for push \";
         cout<<\"\\n\\t \'o\' for pop \";
         cout<<\"\\n\\t \'r\' for print\";
         cout<<\"\\n\\t Any other to exit\"<<endl;

         cin>>ch;

         switch(ch)
        {
           case \'p\':
              entry=new(node);   //  entry=(node*)malloc(sizeof(node));

              cout<<\"enter the element = \";
              cin>>num;

              if(start==NULL)
             {
                entry->data=num;
                entry->next=NULL;
                top=entry;
                start=entry;
                l=0;
             }

              else
             {
                entry->data=num;
                entry->next=NULL;
                top->next=entry;
                top=entry;
             }

              break;

           case \'o\':
              if(start==NULL)
             cout<<\"Nothing to pop\"<<endl;

              else
             {
                for(last=start;last->next!=NULL;last=last->next)
                   last2=last;

                if(top==start)
                   l=1;

                delete(top);       //  free(top);

                if(l==1)
                   start=NULL;

                top=last2;
                top->next=NULL;
             }

              break;

           case \'r\':
              for(print=start;print!=NULL;print=print->next)
             cout<<print->data<<endl;

              getch();
              break;
        }
      }
       while(ch==\'p\' || ch==\'o\' || ch==\'r\');

       getch();
       return 0;
    }

 
 
Didn't find what you were looking for? Find more on Program to illustrate self-referential structures Linked List